I would like to implement a general purpose runtime type conversion function that makes use .Net TypeConverters to do the conversion.
Does anyone know how to how to look up and invoke a TypeConverter for a particular type?
Consider this C# example:
//
// Convert obj to the type specified by 'toType'.
//
object ConvertTo(object obj, Type toType)
{
if (TypeIsEqualOrDerivesFrom(obj.GetType(), toType)) <-- I know how to implement this.
{
// The type of obj is the same as the type specified by 'toType' or
// the type of obj derives from the type specified by 'toType'.
return obj;
}
if (TypeConverterExists(obj.GetType(), toType) <-- How do I implement this?
{
// There exists a type convertor that is capable of converting from
// the type of obj to the type specified by 'toType'.
return InvokeTypeConverter(obj, toType); <-- How do I implement this?
}
throw new TypeConversionFailedException();
}
CanConvertTo(Type) Returns whether this converter can convert the object to the specified type. ConvertFrom(ITypeDescriptorContext, CultureInfo, Object) Converts the given object to the type of this converter, using the specified context and culture information. ConvertFrom(Object)
Type converters let you convert one type to another type. Each type that you declare can optionally have a TypeConverter associated with it using the TypeConverterAttribute. If you do not specify one the class will inherit a TypeConverter from its base class.
Use type converters You support custom types by providing type converters, which are methods that tell Room how to convert custom types to and from known types that Room can persist. You identify type converters by using the @TypeConverter annotation.
I don't know how robust it is, but I sometimes use this code for generic type conversion :
public T ConvertTo<T>(object value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
I don't know if the ChangeType method use TypeConverters...
TypeConverter converter = TypeDescriptor.GetConverter(sourceType);
if(converter.CanConvertTo(destinationType)) {
return converter.ConvertTo(obj, destinationType);
}
converter = TypeDescriptor.GetConverter(destinationType);
if(converter.CanConvertFrom(sourceType)) {
return converter.ConvertFrom(obj);
}
You could also look at Convert.ChangeType(obj, destinationType)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With