如果我有类似的话:
object value = null;
Foo foo = new Foo();
PropertyInfo property = Foo.GetProperties().Single(p => p.Name == "IntProperty");
property.SetValue(foo, value, null);
然后foo.IntProperty
设置为0
,即使value = null
。看起来它正在做IntProperty = default(typeof(int))
之类的事情。如果InvalidCastException
不是“可空”类型(IntProperty
或引用),我想抛出Nullable<>
。我正在使用Reflection,所以我不提前知道类型。我该怎么做呢?
答案 0 :(得分:12)
如果您拥有PropertyInfo
,则可以查看.PropertyType
;如果.IsValueType
为真,并且Nullable.GetUnderlyingType(property.PropertyType)
为空,那么它是一个不可为空的值类型:
if (value == null && property.PropertyType.IsValueType &&
Nullable.GetUnderlyingType(property.PropertyType) == null)
{
throw new InvalidCastException ();
}
答案 1 :(得分:1)
您可以使用PropertyInfo.PropertyType.IsAssignableFrom(value.GetType())表达式来确定是否可以将指定值写入属性。但是当value为null时你需要处理大小写,所以在这种情况下,只有当属性类型为可空或属性类型为引用类型时,才能将它分配给属性:
public bool CanAssignValueToProperty(PropertyInfo propertyInfo, object value)
{
if (value == null)
return Nullable.GetUnderlyingType(propertyInfo.PropertyType) != null ||
!propertyInfo.IsValueType;
else
return propertyInfo.PropertyType.IsAssignableFrom(value.GetType());
}
此外,您可能会发现有用的Convert.ChangeType方法将可转换值写入属性。