PropertyInfo SetValue和nulls

如果我有类似的东西:

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 。 我正在使用Reflection,所以我不提前知道类型。 我该怎么做呢?

如果您有PropertyInfo ,则可以检查.PropertyType ; if .IsValueType为true,如果Nullable.GetUnderlyingType(property.PropertyType)为null,则它是一个不可为空的值类型:

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

您可以使用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方法将可转换值写入属性。