.Net 2+:为什么if(1 == null)不再抛出编译器异常?

Kei*_*ith 5 c# compiler-construction .net-3.5 .net-2.0

我用的int是一个例子,但这适用于.Net中的任何值类型

在.Net 1中,以下内容会引发编译器异常:

int i = SomeFunctionThatReturnsInt();

if( i == null ) //compiler exception here
Run Code Online (Sandbox Code Playgroud)

现在(在.Net 2或3.5中)异常已经消失.

我知道为什么会这样:

int? j = null; //nullable int

if( i == j )   //this shouldn't throw an exception
Run Code Online (Sandbox Code Playgroud)

问题是因为可以int?为空,int现在有一个隐式转换int?.上面的语法是编译魔术.我们真的在做:

Nullable<int> j = null; //nullable int

//compiler is smart enough to do this
if( (Nullable<int>) i == j)   

//and not this
if( i == (int) j)
Run Code Online (Sandbox Code Playgroud)

所以现在,当我们这样做时,i == null我们得到:

if( (Nullable<int>) i == null )
Run Code Online (Sandbox Code Playgroud)

鉴于C#正在进行编译逻辑来计算这个,为什么在处理绝对值时,为什么它不能够聪明null呢?

Ste*_*per 3

我不认为这本身是编译器问题;整数值永远不会为空,但使它们相等的想法并不是无效的;这是一个总是返回 false 的有效函数。编译器知道;代码

bool oneIsNull = 1 == null;
Run Code Online (Sandbox Code Playgroud)

编译,但给出编译器警告:The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type '<null>'

因此,如果您希望返回编译器错误,请转到项目属性并针对此错误打开“将警告视为错误”,然后您将再次开始将它们视为破坏构建的问题。