TypeUtils -- Object 转为 强类型

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));
    }
}

 

posted @ 2016-01-28 11:48  root_u  阅读(589)  评论(0编辑  收藏  举报