看下面的例子:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在示例中,我将int属性设置为null使用反射.我希望这会抛出一个异常,因为null它不是一个有效的值int.但它没有抛出,它只是将属性设置为0.为什么!?
更新
好吧,似乎就是这样.如果尝试将其设置为null,则该属性将获取value-type的默认值.我已经发布了一个答案,描述了我如何解决我的问题,也许有一天会帮助某人.感谢所有回答的人.
| 归档时间: |
|
| 查看次数: |
758 次 |
| 最近记录: |