2010-06-15 58 views
10

如果我有这样的:的PropertyInfo的SetValue和空

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<>或参考)。我正在使用反射,所以我不知道类型提前。我会如何去做这件事?

回答

12

如果你有PropertyInfo,你可以检查.PropertyType;如果.IsValueType为真,并且如果Nullable.GetUnderlyingType(property.PropertyType)为空,则它是一个非空值型:

 if (value == null && property.PropertyType.IsValueType && 
      Nullable.GetUnderlyingType(property.PropertyType) == null) 
     { 
      throw new InvalidCastException(); 
     } 
+0

就是这样。我正在搞.PropertyType.IsClass,但没有太多。 – 2010-06-15 22:42:02

1

可以使用PropertyInfo.PropertyType.IsAssignableFrom(value.GetType())的表达,以确定是否指定的值可以写入财产。但是,你需要的时候值为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将可转换值写入属性的方法。

+0

的SetValue()已经抛出时,它不能设置值,这是期望的行为异常(但它是一个ArgumentException)。我只需要处理null情况。 – 2010-06-15 22:45:27