当我调试几行代码并问我为什么它不起作用时,我偶然发现了这种情况......
if(answer.AnswerID == null)
{
// do something
}
实际上应该是这样的:
if(answer == null)
{
// do something
}
-
answer
是Answer - a class
类型的对象. -
AnswerID
是long
类型的属性.
奇怪的是,如果你尝试这样的事情:
long myLongValue = null;
编译器会报错:
Connot convert null to long ...
所以我的问题是:当我尝试比较 long type
时,为什么没有出现编译错误与 null
?
已编辑
这个问题不是关于nullable
的问题类型。
我在问为什么 .NET 允许我将长变量与 null 进行比较。我说的是 long type
而不是关于 long<b>?</b> type
.
最佳答案
正如 @Tim 所指出的,您不会收到以下代码的错误:
long foo = 42;
if (foo == null) { }
您会收到一条警告:
The result of the expression is always 'false' since a value of type 'long' is never equal to 'null' of type 'long?'.
由于 lifted operators 在 C# 语言规范中这样定义,因此给出警告而不是错误:
Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. [...] For the equality operators
== !=
a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operands are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.
本例中的“底层运算符”是 the predefined value type long
's ==
operator :
For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise.
因为 foo
被隐式转换(“对不可空值类型进行操作的预定义隐式转换也可以与这些类型的可为空形式一起使用。”) 并且 null
文字也被隐式转换( “存在从 null 文字到任何可空类型的隐式转换。”),表达式:
(long)foo == null
变成:
(long?)foo == (long?)null
其中,给定 foo
的类型为 long
,因此始终有一个值,始终返回 false,甚至不会应用 long
的 ==
运算符。
我不完全确定,但我怀疑它的存在是为了在不显式转换的情况下实现可空值和非空值之间的比较:
long? foo = 42;
long bar = 42;
Console.WriteLine(foo == bar); // true
foo = null;
Console.WriteLine(bar == foo); // false
如果这不是由上面指定的语言处理的,你会得到 “运算符 ==
不能应用于类型 long?
和 long
的操作数”,因为 Nullable<T>
没有 ==
运算符,而 long
没有接受 ==
的 long?
运算符。
关于c# - 为什么允许 "long value"等于 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21111534/