知识大全 也谈值类型与null的判等比较
Posted 知
篇首语:苦心人天不负,卧薪尝胆,三千越甲可吞吴。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 也谈值类型与null的判等比较相关的知识,希望对你有一定的参考价值。
首先我们回顾一下代码(这里根据需要做了简化)
using System;
namespace StructOperatorDemo
class Program
struct MyStruct
public int Value;
public MyStruct(int fValue)
this Value = fValue;
public static bool operator !=(MyStruct s MyStruct s )
return s Value != s Value;
public static bool operator ==(MyStruct s MyStruct s )
return s Value == s Value;
static void Main(string[] args)
MyStruct myStruct = new MyStruct();
if (myStruct == null)
Console WriteLine( OMG that is impossible! );
之前的代码用 Net 以及之后的编译器可以编译通过 但是 之前的编译器去编译是无法通过的 它会明确告示你struct不能跟null比较 这是什么原因呢?
我们再看看这段代码
int x = ;
if (x == )
Console WriteLine( Emmm I think it is not possible );
就这段代码而言 虽然int 本身并不包含对double类型判等比较的重载 但无论是新的还是老的 Net编译器都可以编译通过(当然还有加上相关必要的代码) 因为编译器在编译时会将x和 转换成double 来进行比较 对了 编译器自己会做隐式转换
所以第一段代码到了 Net 就可以编译通过 因为二者都可以被转换成MyStruct?进行比较 而在 Net 之前 编译器还不知道什么是Nullable Type呢!
当然 编译器还做了别的优化 比如例子中的情况根本不可能返回true 那么编译器直接忽略随后的相关代码
cha138/Article/program/net/201311/13887相关参考