如果我有类似这样的东西:
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))的事情。如果IntProperty不是“可空的”类型(Nullable<>或引用),我想抛出一个InvalidCastException。我使用的是反射,所以我事先不知道类型。我该怎么做呢?
发布于 2010-06-16 06:21:18
如果您有PropertyInfo,则可以检查.PropertyType;如果.IsValueType为true,并且Nullable.GetUnderlyingType(property.PropertyType)为null,则它是不可为空的值类型:
if (value == null && property.PropertyType.IsValueType &&
Nullable.GetUnderlyingType(property.PropertyType) == null)
{
throw new InvalidCastException ();
}发布于 2010-06-16 06:39:41
您可以使用PropertyInfo.PropertyType.IsAssignableFrom(value.GetType())表达式来确定是否可以将指定的值写入属性。但是您需要处理value为null时的情况,因此在这种情况下,只有当property type为null或property type为reference type时,才能将其赋值给property:
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方法来将可转换的值写入属性。
https://stackoverflow.com/questions/3049477
复制相似问题