可能重复:
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
例子呢?
可能做的很警告你所提到的。编译器可能会将其编译为“if(false)”。哪一个是正确的,'x'永远不能是'null'。 –
学习如何使用'?'这不会编译'int? y =(int)null;'但是在运行时这会编译'int? y =(int?)null;'你明白'?'的作用了吗? – MethodMan
也不会编译'int? z =(int)(int?)null;错误可空类型必须有一个值'但是这会编译'int? z =(int?)(int?)null;'测试出来..祝您好运并且编码愉快 – MethodMan