使用 FieldInfo.SetValue 将 ValueType 设置为 null 不应该失败吗?
(与 PropertyInfo SetValue 和 nulls 相关)
如果我有 public class Thing { public int X; }
,一个Thing o
,还有一个指向X
字段的FieldInfo fi
,为什么调用是合法的>fi.SetValue(o, null)
?运行时将字段 X
设置为零,即 default(int)
,而不是抱怨 ValueType
无法设置为 null< /代码>。
有谁知道这种行为背后的设计选择,至少从 C# 来看,这违反了我的最小惊讶原则?
(related to PropertyInfo SetValue and nulls)
If I have public class Thing { public int X; }
, a Thing o
, and a FieldInfo fi
that points to the X
field, why is it legal to call fi.SetValue(o, null)
? The runtime sets the field X
to zero, i.e. default(int)
instead of complaining that a ValueType
cannot be set to null
.
Does anyone know the design choice behind this behavior, which at least from C# violates my principle of least astonishment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ArgumentException
的“异常”框中包含的文本表明传入的值需要进行转换,这可以解释其成功的原因。我确实同意这看起来有点奇怪,特别是因为我通常期望反射 API 是更严格和更不宽容的 API 之一。
您可以尝试联系 Eric Lippert ,虽然这是 BCL/ CLR 问题而不是 C# 问题,他有可能知道答案或认识知道答案的人。要么能够给出很好的猜测。
The text contained in the Exceptions box for
ArgumentException
suggests that the value passed in is subject to conversion, which would explain why it succeeds.I do agree that it seems slightly strange, particularly as I generally expect the reflection APIs to be one of the more rigid and less forgiving.
You might try contacting Eric Lippert , whilst this is a BCL/CLR question rather than C#, there's a chance he'll know the answer or know someone who does. Either that or be able to give a very good guess.