【发布时间】:2010-09-08 22:08:18
【问题描述】:
我以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 这样的绝对值时不这样做?
【问题讨论】:
标签: c# .net-3.5 compiler-construction .net-2.0