将'int'与'null'进行比较编译

rhu*_*hes 7 c#

可能重复:
C#可以将值类型与null进行比较

我刚刚在C#(4.0)编译器中遇到了一些奇怪的东西.

int x = 0;
if (x == null) // Only gives a warning - 'expression is always false'
    x = 1;

int y = (int)null; // Compile error
int z = (int)(int?)null; // Compiles, but runtime error 'Nullable object must have a value.'
Run Code Online (Sandbox Code Playgroud)

如果你不能分配nullint,为什么编译器允许你比较它们(它只给出一个警告)?

有趣的是,编译器不允许以下内容:

struct myStruct
{
};

myStruct s = new myStruct();
if (s == null) // does NOT compile
    ;
Run Code Online (Sandbox Code Playgroud)

为什么struct示例不能编译,但int示例呢?

Jef*_*ado 6

进行比较时,编译器会尝试进行比较,以便比较的两个操作数都具有兼容的类型(如果可能).

它有一个int值和一个常null量值(没有特定的类型).两个值之间唯一的兼容类型int?是强制转换int?并进行比较int? == int?.一些intint?肯定是非null并且null绝对是null.编译器意识到并且由于非空值不等于确定null值,因此给出了警告.