我在 MSDN 上读到:
The null keyword is a literal that represents a null reference, one that does not refer to any object.
但是我看到下面的代码运行时没有抛出任何异常:
int? i = null;
var s = i.ToString();
那么如果变量i
为null,为什么我可以执行它的方法呢?
最佳答案
因为 int?
实际上是一个 Nullable<Int32>
和 Nullable<T>
是 struct
, 和一个结构 cannot be null .
就是这样Nullable types work.它们不是引用值,所以它们不能为空,但当它们被认为等同于空时,它们可以有一个状态。
您可以获得有关Nullable<T>
的更多详细信息在 how are nullable types implemented under the hood in .net? 中实现和 Nullable<T> implementation
虽然正如@JeppeStigNielsen 所指出的,但在一种情况下您可以获得 NRE:
However: When boxed to a reference type, special treatment of Nullable<> ensures we do get a true null reference. So for example i.GetType() with i as in the question will blow up with the NullReferenceException. That is because this method is defined on object and not overridable
关于c# - 我怎么能在int上执行方法?在没有 NullReferenceException 的情况下设置为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837684/