使用反射将值类型设置为null时出现奇怪的行为,为什么?

4

请看以下示例:

public class Test {
    public int Number { get; set; }
    public void TestReflection() {
        Number = 99;
        Type type = GetType();
        PropertyInfo propertyInfo = type.GetProperty("Number");
        propertyInfo.SetValue(this, null, null);
    }
}

在这个示例中,我使用反射将一个int属性设置为null。我原本期望会抛出异常,因为null不是int类型的有效值。但是它没有抛出异常,而是将属性设置为0。为什么会这样呢?
更新
好吧,看来就是这样。如果你尝试将value-type类型的属性设置为null,它会得到默认值。我已经发布了一个回答,描述了我如何解决我的问题,也许这会在将来帮助某些人。谢谢所有回答的人。
3个回答

8

这可能是将值设置为类型的默认值。我认为布尔值也会变为false。

与使用以下内容相同:

default(int);

我在MSDN中找到了一些关于C#中默认关键字的文档。

6
它设置了该类型的默认值。这种行为在之前的文档中没有提到,但现在已经明确说明了:
如果此PropertyInfo对象是值类型且值为null,则该属性将被设置为该类型的默认值。

2

SetValue方法(或者默认绑定程序)的行为似乎有些危险,以下代码可以解决我的问题:

public class Test {
    public int Number { get; set; }
    public void SetNumberUsingReflection(object newValue) {
        Number = 99;
        Type type = GetType();
        PropertyInfo propertyInfo = type.GetProperty("Number");
        if(propertyInfo.PropertyType.IsValueType && newValue == null) {
            throw new InvalidOperationException(String.Format("Cannot set a property of type '{0}' to null.", propertyInfo.PropertyType));
        } else {
            propertyInfo.SetValue(this, newValue, null);
        }
    }
}

也许有一天它会帮助到某个人......

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接