我有一个用 a 装饰的基类,TypeDescriptionProviderAttribute
它指向ICustomTypeDescriptor
.
有一个派生类装饰有一个TypeConverterAttribute
做自定义类型转换。
BaseClassTypeDescriptor
通过ICustomTypeDescriptor.GetConverter
调用静态TypeDescriptor.GetConverter
方法来实现。该方法有两个参数:有问题的类型(我有一个引用)和一个指示是否允许调用自定义行为的标志。这必须设置为true
防止无限循环。
代码的精简版本如下所示:
[TypeDescriptionProvider(typeof(BaseClassTypeDescriptionProvider))]
public class BaseClass
{
public class BaseClassTypeDescriptionProvider : TypeDescriptionProvider
{
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType_, object instance_)
{
return new BaseClassTypeDescriptor(objectType_);
}
}
public class BaseClassTypeDescriptor : ICustomTypeDescriptor
{
private Type _type;
public BaseClassTypeDescriptor(Type type_)
{
_type = type_;
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(_type, true);
}
}
}
[TypeConverter(typeof(MyTypeConverter))]
public class DerivedClass : BaseClass
{
}
问题是这个标志似乎不仅绕过BaseClassTypeDescriptor
,而且似乎阻止 .NET 识别TypeConverterAttribute
派生类上的 。
TypeConverterAttribute
我已经通过重新实现对我的实现内部的检查来解决这个问题MyCustomTypeConverter.GetConverter
,如下所示:
TypeConverter ICustomTypeDescriptor.GetConverter()
{
object[] typeConverterAttributeArray = _type.GetCustomAttributes(typeof(TypeConverterAttribute), true);
if (typeConverterAttributeArray.Length == 1)
{
TypeConverterAttribute a = (TypeConverterAttribute)typeConverterAttributeArray[0];
Type converterType = MyTypeLoader.GetType(a.ConverterTypeName);
return (TypeConverter)Activator.CreateInstance(converterType);
}
else
{
return TypeDescriptor.GetConverter(_type, true);
}
}
这远非理想的解决方案。关于如何将责任委托给它所属的地方有什么建议吗?