首先我们回顾一下代码(这里根据需要做了简化) using System;
namespace StructOperatorDemo { class Program { struct MyStruct { public int Value;
public MyStruct(int fValue) { thisValue = fValue; }
public static bool operator !=(MyStruct s MyStruct s) { return sValue != sValue; } public static bool operator ==(MyStruct s MyStruct s) { return sValue == sValue; } }
static void Main(string[] args) { MyStruct myStruct = new MyStruct();
if (myStruct == null) { ConsoleWriteLine(OMG that is impossible!); } } } } 之前的代码用Net以及之后的编译器可以编译通过但是 之前的编译器去编译是无法通过的它会明确告示你struct不能跟null比较这是什么原因呢? 我们再看看这段代码 int x = ;
if (x == ) { ConsoleWriteLine(Emmm I think it is not possible); } 就这段代码而言虽然int 本身并不包含对double类型判等比较的重载但无论是新的还是老的Net编译器都可以编译通过(当然还有加上相关必要的代码)因为编译器在编译时会将x和转换成double 来进行比较对了编译器自己会做隐式转换 所以第一段代码到了Net就可以编译通过因为二者都可以被转换成MyStruct?进行比较而在Net 之前编译器还不知道什么是Nullable Type呢! 当然编译器还做了别的优化比如例子中的情况根本不可能返回true那么编译器直接忽略随后的相关代码 就象周雪峰同学总结的那样这不是一个bug而是故意设计的而真相则是对Nullable Type隐式转换的一个延伸虽然struct == null不可能发生但是它是合法的 : ) |