2010-06-18 28 views

回答

17

嗯,不知道我以前見過,但你可以使用TypeDescriptor在運行時添加的TypeConverterAttribute,所以給我的示例類:

public class MyType 
{ 
    public string Name; 
} 

public class MyTypeConverter : TypeConverter 
{ 
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 
    { 
     if (sourceType == typeof(string)) 
      return true; 

     return base.CanConvertFrom(context, sourceType); 
    } 

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) 
    { 
     if (value.GetType() == typeof(string)) 
      return new MyType() { Name = (string) value }; 

     return base.ConvertFrom(context, culture, value); 
    } 
} 

然後我可以有一個方法:

public void AssignTypeConverter<IType, IConverterType>() 
{ 
    TypeDescriptor.AddAttributes(typeof(IType), new TypeConverterAttribute(typeof(IConverterType))); 
} 

AssignTypeConverter<MyType, MyTypeConverter>(); 

希望有幫助。

+0

但是,這對於XAML **不起作用,因爲XAML在運行時不考慮組件修改。我[使用'TypeConverter'找到了解決方法](https://whathecode.wordpress.com/2015/02/14/generic-typeconverter/),它將其實現重定向到使用TypeDescriptor加載的轉換器。 – 2015-02-14 18:01:26

3

您仍然可以使用TypeConverterAttribute並使用它的接受完全限定名稱的構造函數。請參閱MSDN

+0

難道這仍然不需要引用包含typeconverter的程序集? – Spike 2010-06-21 01:27:53

+0

不,包含typeconverter的程序集將在運行時通過Type.GetType(http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx)加載。 – Patko 2010-06-21 07:10:10

+0

@Spike,不,因爲類型轉換器類型可以通過名稱而不是typeof(...)引用。 – yoyo 2014-01-03 02:14:59

相關問題