C# PropertyInfo SetValue和nulls

C# PropertyInfo SetValue和nulls,c#,reflection,default,C#,Reflection,Default,如果我有类似于: 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)

如果我有类似于:

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”类型(
nullable
或引用),我想抛出一个
InvalidCastException
)。我使用的是反射,所以我事先不知道类型。我该怎么做呢?

如果您有
属性info
,您可以检查
.PropertyType
;如果
.IsValueType
为true,并且
可为null。GetUnderlyingType(property.PropertyType)
为null,则它是不可为null的值类型:

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

可以使用PropertyInfo.PropertyType.IsAssignableFrom(value.GetType())表达式确定是否可以将指定的值写入属性。但当值为null时,您需要处理大小写,因此在这种情况下,只有当属性类型为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方法将可转换值写入属性。

就是这样。我正在处理.PropertyType.IsClass,但没有走多远。SetValue()在无法设置值时已引发异常,这是所需的行为(但它是ArgumentException)。我只需要处理空场景。