我有一個基類,用TypeDescriptionProviderAttribute
裝飾,指向一個自定義實現ICustomTypeDescriptor
。ICustomTypeDescriptor GetConverter實現
有一個派生類用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
類。
我已經重新實現了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);
}
}
這是遠遠的理想解決方案。任何關於我如何將責任委託歸屬的建議?