Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeConverter Attribute for Third Party Classes

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

like image 534
TRISAbits Avatar asked Dec 18 '12 00:12

TRISAbits


1 Answers

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)));
like image 50
Mir Avatar answered Oct 14 '22 08:10

Mir