我有一个用TypeDescriptionProviderAttribute装饰的基类,它指向ICustomTypeDescriptor的自定义实现。
有一个用TypeConverterAttribute修饰的派生类来执行自定义类型转换。
BaseClassTypeDescriptor通过调用静态TypeDescriptor.GetConverter方法来实现ICustomTypeDescriptor.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。
为此,我在MyCustomTypeConverter.GetConverter实现中重新实现了对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);
}
}这远远不是一个理想的解决办法。关于我如何将责任下放到属于它的地方,有什么建议吗?
发布于 2015-05-07 18:43:06
在您的示例中,TypeDescriptor.GetConverter(object component, bool noCustomTypeDesc)的重载似乎返回Type类型的TypeDescriptor,因为它需要一个实例。
我试过你的例子
return TypeDescriptor.GetConverter(Activator.CreateInstance(_type), true);得到了bool值应该防止的无限循环。
我不知道为什么会这样工作,也不知道这是否以某种方式被记录下来,但我敢打赌,他们根本不希望TypeDescriptionProvider调用TypeDescriptor.GetConverter()。
https://stackoverflow.com/questions/30108258
复制相似问题