<分区>
Possible Duplicate:
C# okay with comparing value types to 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.'
如果您不能将null
分配给int
,为什么编译器允许您比较它们(它只给出警告)?
有趣的是,编译器不允许以下内容:
struct myStruct
{
};
myStruct s = new myStruct();
if (s == null) // does NOT compile
;
为什么 struct
示例无法编译,而 int
示例可以?