可能是重复问题:
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.'
如果你不能将null
赋值给一个int
,为什么编译器允许你比较它们(只会给出警告)?
有趣的是,编译器不允许以下操作:
struct myStruct
{
};
myStruct s = new myStruct();
if (s == null) // does NOT compile
;
为什么
struct
的例子不能编译通过,但是int
的例子可以呢?
if (false)
。这是正确的,x
永远不可能是null
。 - Simon Whiteheadint? z = (int)(int?)null; Error Nullable type must have a value
。但是,这段代码可以编译通过:int? z = (int?)(int?)null;
试一下吧,祝你好运,编码愉快! - MethodManint z = (int)(int?)null;
可以编译通过。我理解?
的含义,但我的问题与if (x == null)
有关。 - rhughesint?
(可空类型)。由于int
可以转换为int?
,所以这将编译通过,但始终为false,基本上它选择了最佳的运算符重载,在这种情况下,由于右侧为空,它选择了int? == int?
。 - sa_ddam213