2010-06-15 55 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