对于第三方类的TypeConverter属性第三方、属性、TypeConverter

2023-09-03 04:54:15 作者:偏执的傲

在创建类,的TypeConverter属性可应用于它圣使用TypeDescriptor.GetConverter(typeof运算(T))返回自定义类型转换器。例如:

When creating a class, a TypeConverter attribute can be applied to it s.t. using TypeDescriptor.GetConverter(typeof(T)) return the custom type converter. For instance:

[TypeConverter(typeof(FooConverter))]
public class Foo
{...}

public class FooConverter: TypeConverter
{...}

var tc = TypeDescriptor.GetConverter(typeof(T)); //returns a FooConverter instance.

这工作只要类是我们造成的。但是,如何将一个提供自定义类型转换器对此我们不能修改源$ C ​​$ C类?例如,如何能提供自定义的TypeConverter为所述System.Version类(其不具有一个)?

This works as long as the class is of our making. But how would one provide a custom TypeConverter for a class which we cannot modify the source code? For example, how would one provide a custom TypeConverter for the the System.Version class (which does not have one)?

推荐答案

您可以在运行时做到这一点。有了这些类:

You can do it at runtime. With these classes:

class MyConverter : TypeConverter
{
}

sealed class MyClass
{   
}

您可以使用:

TypeDescriptor.AddAttributes(typeof(MyClass), new TypeConverterAttribute(typeof(MyConverter)));
 
精彩推荐