2015-05-07 15 views
1

我有一個基類,用TypeDescriptionProviderAttribute裝飾,指向一個自定義實現ICustomTypeDescriptorICustomTypeDescriptor 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); 
    } 
} 

這是遠遠的理想解決方案。任何關於我如何將責任委託歸屬的建議?

回答

0

在您的示例中,TypeDescriptor.GetConverter(object component, bool noCustomTypeDesc)的超載似乎返回Type類型的TypeDescriptor,因爲它需要一個實例。

我想你的榜樣與

return TypeDescriptor.GetConverter(Activator.CreateInstance(_type), true); 

,並得到了無限循環的bool值應該避免。

我不知道爲什麼這這種方式工作的,以及是否以某種方式記錄,但我敢打賭,他們不希望一個TypeDescriptionProvider打電話TypeDescriptor.GetConverter()可言。

相關問題