美文网首页
System.Convert.ChangeType, 使其能够转

System.Convert.ChangeType, 使其能够转

作者: flyinghat | 来源:发表于2019-10-12 15:28 被阅读0次

    以下是微软技术资源库的解说: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);
            }
    
    

    相关文章

      网友评论

          本文标题:System.Convert.ChangeType, 使其能够转

          本文链接:https://www.haomeiwen.com/subject/wtmiectx.html