使用 FieldInfo.SetValue 将 ValueType 设置为 null 不应该失败吗?

发布于 2024-09-16 11:54:34 字数 484 浏览 5 评论 0原文

(与 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黒涩兲箜 2024-09-23 11:54:34

ArgumentException 的“异常”框中包含的文本表明传入的值需要进行转换,这可以解释其成功的原因。

value参数无法转换并存储在字段中。

我确实同意这看起来有点奇怪,特别是因为我通常期望反射 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.

The value parameter cannot be converted and stored in the field.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文