C#把对象类型转化为指定类型,转化失败时返回该类型默认值

/// <summary>
    ///通用类型扩展方法类
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        ///把对象类型转化为指定类型,转化失败时返回该类型默认值
        /// </summary>
        /// <typeparam name=”T”> 动态类型 </typeparam>
        /// <param name=”value”> 要转化的源对象 </param>
        /// <returns> 转化后的指定类型的对象,转化失败返回类型的默认值 </returns>
        public static T CastTo<T>(this object value)
        {
            object result;
            Type type = typeof(T);
            try
            {
                if (type.IsEnum)
                {
                    result = Enum.Parse(type, value.ToString());
                }
                else if (type == typeof(Guid))
                {
                    result = Guid.Parse(value.ToString());
                }
                else
                {
                    result = Convert.ChangeType(value, type);
                }
            }
            catch
            {
                result = default(T);
            }

            return (T)result;
        }

        /// <summary>
        ///     把对象类型转化为指定类型,转化失败时返回指定的默认值
        /// </summary>
        /// <typeparam name=”T”> 动态类型 </typeparam>
        /// <param name=”value”> 要转化的源对象 </param>
        /// <param name=”defaultValue”> 转化失败返回的指定默认值 </param>
        /// <returns> 转化后的指定类型对象,转化失败时返回指定的默认值 </returns>
        public static T CastTo<T>(this object value, T defaultValue)
        {
            object result;
            Type type = typeof(T);
            try
            {
                result = type.IsEnum ? Enum.Parse(type, value.ToString()) : Convert.ChangeType(value, type);
            }
            catch
            {
                result = defaultValue;
            }
            return (T)result;
        }
    }

    原文作者:菜刀2008
    原文地址: https://blog.csdn.net/y_f123/article/details/39251719
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞