我怎么能在int上执行方法?在没有 NullReferenceException 的情况下设置为 null?
How is it that can I execute method on int? set to null without NullReferenceException?
我在 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>
is a struct
, and a structure cannot be null.
就是这样Nullable types work.它们不是引用值,所以不能为null,但是当它们被认为等价于null时,它们可以有一个状态。
您可以在 how are nullable types implemented under the hood in .net? and Nullable<T> implementation
中获得有关 Nullable<T>
实施的更多详细信息
虽然正如@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
您粘贴的代码
int? i = null;
实际上只是shorthand for
int? i = new int?();
这是
的 shorthand
Nullable<int> i = new Nullable<int>();
分配 null 是使用隐式运算符,您可以从此处阅读更多内容 MSDN。
我在 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>
is a struct
, and a structure cannot be null.
就是这样Nullable types work.它们不是引用值,所以不能为null,但是当它们被认为等价于null时,它们可以有一个状态。
您可以在 how are nullable types implemented under the hood in .net? and Nullable<T> implementation
中获得有关Nullable<T>
实施的更多详细信息
虽然正如@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
您粘贴的代码
int? i = null;
实际上只是shorthand for
int? i = new int?();
这是
的 shorthandNullable<int> i = new Nullable<int>();
分配 null 是使用隐式运算符,您可以从此处阅读更多内容 MSDN。