我int
以示例为例,但这适用于 .Net 中的任何值类型
在 .Net 1 中,以下内容会引发编译器异常:
int i = SomeFunctionThatReturnsInt();
if( i == null ) //compiler exception here
现在(在 .Net 2 或 3.5 中)该异常已经消失。
我知道这是为什么:
int? j = null; //nullable int
if( i == j ) //this shouldn't throw an exception
问题是因为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)
所以现在,当我们这样做时,i == null
我们得到:
if( (Nullable<int>) i == null )
鉴于 C# 正在执行编译器逻辑来计算这个,为什么在处理绝对值时不能足够聪明地不这样做null
?