gpt4 book ai didi

c# - 可空类型 GetType() 抛出异常

转载 作者:可可西里 更新时间:2023-11-01 08:59:32 24 4
gpt4 key购买 nike

我刚刚从一个同事那里得到了这个让我发疯的测验。对于这段代码:

var x = new Int32?();
string text = x.ToString(); // No exception
Console.WriteLine(text);
Type type = x.GetType(); // Bang!

为什么第一部分 .ToString() 工作时没有抛出异常,然后调用 GetType() 抛出 NullReferenceException?

最佳答案

ToStringoverridden in Nullable<T> , 因此调用时不涉及装箱。

GetType()不是虚方法,因此不会(也不能)被重写,因此在调用之前将值装箱...并且装箱可为空值类型的空值提供空引用。

装箱的原因在 C# 4 规范的第 7.5.5 节中:

If M is an instance function member declared in a reference-type:

  • ...
  • If the type of E is a value-type, a boxing conversion (4.3.1) is performed to convert E to type object, and E is considered to be of type object in the following steps. In this case, M could only be a member of System.Object

请注意,如果您有:

var x = new Int32?(10);

你最终会得到与 typeof(int) 相同的类型,又是由于拳击。无法创建值 foo这样 foo.GetType()使用普通的 GetType() 返回可空值类型方法。 (您当然可以创建一个 GetType() 方法,但这是一个附带问题:)

(使用“Bang!”表明上述测验的作者可能是我。如果是这样的话,很抱歉让你发疯。)

关于c# - 可空类型 GetType() 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12725631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com