TypeUtils — Object 转为 强类型

作者: howie 分类: 工具类 发布时间: 2017-09-07 14:59

public static class TypeUtils
{
/// <summary>
/// Object 转为 强类型
/// </summary>
public static T ConvertType<T>(object value)
{
if (value == null)
return default(T);

var typeConverter = TypeDescriptor.GetConverter(typeof(T));
if (typeConverter.CanConvertFrom(value.GetType()))
{
return (T)typeConverter.ConvertFrom(value);
}

typeConverter = TypeDescriptor.GetConverter(value.GetType());
if (typeConverter.CanConvertTo(typeof(T)))
{
return (T)typeConverter.ConvertTo(value, typeof(T));
}

return (T)Convert.ChangeType(value, typeof(T));
}
}