定义一个类
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