System.Convert.ChangeType, 使其能够转换枚举ENUM和可空类型Nullable

以下是微软技术资源库的解说:http://technet.microsoft.com/zh-cn/library/system.convert.changetype
ChangeType 是将 value 指定的对象转换为 conversionType 的通用转换方法。 value 参数可以是任何类型的对象,conversionType 也可以是表示任何基类型或自定义类型的 Type 对象。要使转换成功,value 必须实现 IConvertible 接口,因为此方法只是包装对相应 IConvertible 方法的调用。 此方法要求支持将 value 转换为 conversionType。

         /// <summary>
        /// 为模型的单个属性赋值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="PropertyName"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool SetVal(object obj, string PropertyName, object val)
        {
            PropertyDescriptorCollection PropertyCollection = TypeDescriptor.GetProperties(obj);
            if (PropertyCollection.Count > 0)
            {
                PropertyDescriptor Property = PropertyCollection[PropertyName];
                if (Property != null)
                {
                    var temp = ChangeType(val, Property.PropertyType);
                    Property.SetValue(obj, temp);
                    return true;
                }
            }
            return false;
        }
         /// <summary>
        /// 类型转换
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static object ChangeType(object obj, Type type)
        {
            Type nulltype = Nullable.GetUnderlyingType(type);
            if (nulltype != null)
            {
                if (obj == null)
                {
                    return null;
                }
                return Convert.ChangeType(obj, nulltype, Thread.CurrentThread.CurrentCulture);
            }
            if (typeof(System.Enum).IsAssignableFrom(type))
            {
                return Enum.Parse(type, obj.ToString());
            }
            return Convert.ChangeType(obj, type, Thread.CurrentThread.CurrentCulture);
        }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容