c#中有统一的类型转换函数
Convert.ChangeType(object value, Type conversionType)
但是这个函数没有考虑到转换null, DBNull, Nullable<>, Enum这些类型
下面通过扩展ChangeType来实现上述类型的转换
public static object Convert(object value, Type conversionType)
{
if (value == null || value is DBNull)
return null;
if (conversionType.IsInstanceOfType(value))
return value;
if (conversionType.IsEnum)
{
var s = value as string;
if (s != null)
{
return Enum.Parse(conversionType, s);
}
return Enum.ToObject(conversionType, value);
}
var t = Nullable.GetUnderlyingType(conversionType) ?? conversionType;
return System.Convert.ChangeType(value, t);
}