I have written all these wonderful custom TypeConverter for my enums
to display in a PropertyGrid. I would now like to use the same
TypeConverter to save out and read in the values to and from a text
file, in a generic fashion. I would like to have a function like
this:
void WriteValue(StreamWriter sw, string name, Enum value);
Cartoper - 28 Mar 2008 18:54 GMT
As I walked to lunch it dawned on me that I might be able to get at
the attributes via the GetType() method. Well, I wasn't able to, but
I did realize that as long as you follow the convention of <enum
name>TypeConverter, that through reflections you can instanciate the
enum's TypeConverter:
// start by using the default ToString method
string valueStr = Value.ToString();
try
{
// Get the enum type
Type enumType = Value.GetType();
// Get the enum name and then add the TypeConverter to the end of it
string typeConverterName = enumType.FullName + "TypeConverter";
// Get the assembly that the enum is in.
string assemblyName = enumType.Assembly.FullName;
// try to create the type converter
ObjectHandle objHandle =
Thread.GetDomain().CreateInstance(assemblyName, typeConverterName);
// Get the TypeConverter from the object handle
TypeConverter typeConverter = objHandle.Unwrap() as TypeConverter;
// Convert it to a string
valueStr = typeConverter.ConvertToString(Value);
}
catch(Exception)
{
}
Marc Gravell - 28 Mar 2008 19:40 GMT
Or just TypeDescriptor.GetConverter(enumType) ;-p
Marc Gravell - 28 Mar 2008 19:43 GMT
or in fact TypeDescriptor.GetConverter(Value);
I'm also assuming that the enum is marked with TypeConverterAttribute
Marc
Cartoper - 31 Mar 2008 14:20 GMT
> or in fact TypeDescriptor.GetConverter(Value);
>
> I'm also assuming that the enum is marked with TypeConverterAttribute
>
> Marc
Marc,
Where where you Friday, you could have saved me a lot of work;)
Thanks for the tip!
Marc Gravell - 31 Mar 2008 14:31 GMT
No problem; and for the record I replied on Friday!
Marc
Cartoper - 31 Mar 2008 16:01 GMT
> for the record I replied on Friday!
Opps, I guess I ment: where were you while I was at lunch on Firday;)
hehehehehe