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
    }

  

相关文章:

  • 2021-12-17
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
  • 2022-12-23
  • 2022-03-01
  • 2022-12-23
  • 2021-10-11
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-24
  • 2021-08-29
  • 2022-12-23
相关资源
相似解决方案