反射赋值 比如 int?

来源:互联网 发布:墨子号 知乎 编辑:程序博客网 时间:2024/05/02 04:27
 定义一个类
public class P    {        public int Age { get; set; }    }


反射赋值时:

 PropertyInfo pi = p.GetType().GetProperties()[0];            Type piType = pi.PropertyType;            object value;            value = Convert.ChangeType("1", pi.PropertyType, null);            pi.SetValue(p, value, null);
这样 OK


但是如果 将P中的属性 Age  改变

public class P    {        public int? Age { get; set; }    }
此时会报错!!!!!!!


解决办法:

value = Convert.ChangeType(a, (Nullable.GetUnderlyingType(piType) ?? piType));

注意: 此时 piType 是 pi.PropertyType

0 0