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 t
Here's the code used in one of our existing apps... not sure if it's ideal but it works well for us.
///
/// Attempts to convert a value using any customer TypeConverters applied to the member
///
/// Object containing the value to be assigned
/// Member to be assigned to
/// converted to the appropriate type
public static Object CustomTypeConversion ( object value, MemberInfo member )
{
if ( value == null || value == DBNull.Value )
return value;
if ( member == null )
throw new ArgumentNullException ( );
List converters = GetCustomTypeConverters ( member );
foreach ( TypeConverter c in converters )
{
if ( c.CanConvertFrom ( value.GetType ( ) ) )
return c.ConvertFrom ( value );
}
if ( member is PropertyInfo )
{
PropertyInfo prop = member as PropertyInfo;
return ConvertToNative( value , prop.PropertyType );
}
return ConvertToNative ( value, member.MemberType.GetType ( ) );
}
///
/// Extracts and instantiates any customer type converters assigned to a
/// derivitive of the property
///
/// Any class deriving from MemberInfo
/// A list of customer type converters, empty if none found
public static List GetCustomTypeConverters ( System.Reflection.MemberInfo member )
{
List result = new List();
try
{
foreach ( TypeConverterAttribute a in member.GetCustomAttributes( typeof( TypeConverterAttribute ) , true ) )
{
TypeConverter converter = Activator.CreateInstance( Type.GetType( a.ConverterTypeName ) ) as TypeConverter;
if ( converter != null )
result.Add( converter );
}
}
catch
{
// Let it go, there were no custom converters
}
return result;
}
///
/// Attempts to cast the incoming database field to the property type
///
/// Database value to cast
/// Type to cast to
/// The converted value, if conversion failed the original value will be returned
public static object ConvertToNative ( object value , Type castTo )
{
try
{
return Convert.ChangeType( value , castTo , System.Threading.Thread.CurrentThread.CurrentCulture );
}
catch
{
return value;
}
}
Just call the CustomTypeConversion method and away you go... probably a little more than you need but being thorough isn't a crime (or is it?).