把对象类型转换成指定的类型帮助类方法

public static class ObjectExtensions
    {
        #region 把对象类型转换成指定的类型,转化失败时返回指定默认值
        /// <summary>
        /// 把对象类型转换成指定的类型,转化失败时返回指定默认值
        /// </summary>
        /// <typeparam name="T">动态类型</typeparam>
        /// <param name="value">要转换的原对象</param>
        /// <param name="detaultValue">转换失败时返回的默认值</param>
        /// <returns>转化后指定类型对象,转化失败时返回指定默认值</returns>
        public static T CastTo<T>(this object value, T detaultValue)
        {
            object result;
            Type t = typeof(T);
            try
            {
                result = t.IsEnum ? System.Enum.Parse(t, value.ToString()) : Convert.ChangeType(value, t);

            }
            catch (Exception)
            {
                return detaultValue;
            }

            return (T)result;
        }
        #endregion

        #region 把对象类型转换成指定的类型,转化失败时返回类型默认值
        /// <summary>
        /// 把对象类型转换成指定的类型,转化失败时返回类型默认值
        /// </summary>
        /// <typeparam name="T">动态类型</typeparam>
        /// <param name="value">要转换的原对象</param>
        /// <returns>转化后指定类型对象,转化失败时返回类型默认值</returns>
        public static T CastTo<T>(this object value)
        {
            object result;
            Type t = typeof(T);
            try
            {
                if (t.IsEnum)
                {
                    result = System.Enum.Parse(t, value.ToString());
                }
                else if (t == typeof(Guid))
                {
                    result = Guid.Parse(value.ToString());
                }
                else
                {
                    result = Convert.ChangeType(value, t);
                }

            }
            catch (Exception)
            {
                result = default(T);
            }

            return (T)result;
        }
        #endregion
    }

  

posted @ 2016-12-30 15:13  大师兄丶  阅读(556)  评论(0编辑  收藏  举报