TypeConverter Attribute for Third Party Classes

别来无恙 提交于 2019-12-08 14:44:42

问题


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.

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)?


回答1:


You can do it at runtime. With these classes:

class MyConverter : TypeConverter
{
}

sealed class MyClass
{   
}

You can use:

TypeDescriptor.AddAttributes(typeof(MyClass), new TypeConverterAttribute(typeof(MyConverter)));


来源:https://stackoverflow.com/questions/13924494/typeconverter-attribute-for-third-party-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!