反射用法要点
该属性类型是未知非泛型类型,不确定目标类型,如何进行类型转换。
object value="500";
property.SetValue(obj,Convert.ChangeType(value,property.PropertyType),null);//类型转换。
这样就可以解决大多数问题了。
不知道大家有没有注意,我在第三种情况强调了非泛型,难道泛型就不行了吗?
是的。如果只是用Convert.ChangeType()方法,类型转换仍然报错,先看下面的代码。
即使目标类型和值的类型是一致,通过Convert.ChangeType()进行转换仍然报错。
解决这个问题,就要先把属性值类型转成基类型后,在进行Convert转换。看代码
这样,在使用Convert.ChangeType()转换可空类型时,就不会报错了。
再增加一些基础的判断验证,代码就比较完善了。
if (!property.PropertyType.IsGenericType)
{
//非泛型
property.SetValue(obj, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, property.PropertyType), null);
}
else
{
//泛型Nullable<>
Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
property.SetValue(obj, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(property.PropertyType)), null);
}
}