C# ICustomTypeDescriptor GetConverter实现
我有一个用C# ICustomTypeDescriptor GetConverter实现,c#,winforms,icustomtypedescriptor,C#,Winforms,Icustomtypedescriptor,我有一个用TypeDescriptionProviderAttribute修饰的基类,该属性指向ICustomTypeDescriptor的自定义实现 有一个派生类用TypeConverterAttribute修饰以进行自定义类型转换 BaseClassTypeDescriptor通过调用静态TypeDescriptor.GetConverter方法实现ICustomTypeDescriptor.GetConverter。该方法有两个参数:有问题的类型(我有一个引用),以及一个指示是否允许调用自
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
实现中重新实现对TypeConverterAttribute
的检查来解决这个问题,如下所示:
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);
}
}
这远远不是一个理想的解决方案。关于如何将该职责委派回其所属位置的任何建议?在您的示例中,
TypeDescriptor.GetConverter(对象组件,bool noCustomTypeDesc)
的重载似乎返回了类型的TypeDescriptor
,因为它需要一个实例
我试过你的例子
return TypeDescriptor.GetConverter(Activator.CreateInstance(_type), true);
得到了bool
值应该阻止的无限循环
我不知道为什么会这样,也不知道是否以某种方式记录了这一点,但我打赌他们根本不希望TypeDescriptionProvider
调用TypeDescriptor.GetConverter()