c# - 为什么允许 "long value"等于 null?

标签 c# .net

当我调试几行代码并问我为什么它不起作用时,我偶然发现了这种情况......

if(answer.AnswerID == null) 
{
    // do something
}

实际上应该是这样的:

if(answer == null)
{
    // do something
}
  • answerAnswer - a class 类型的对象.
  • AnswerIDlong 类型的属性.

奇怪的是,如果你尝试这样的事情:

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/

相关文章:

c# - 将代码从 .aspx 文件移动到 .cs 文件,没有任何区别

c# - 如何进行一系列异步调用,然后使用第一个线程返回的值?

c# - WPF UserControl Dependency Property Setter 未触发

.net - 将系统错误转换为友好的消息

c# - 使用 C# 在生成器设计模式中集成序列化和反序列化

c# - 无法为此文件显示设计器,因为无法设计其中的任何类

c# - uwp 解析或反序列化 httpclient 响应

c# - 编译可与预处理器指令一起使用的可移植类库时是否有任何符号

.net - 在 .NET 中发送电子邮件,电子邮件保存在用户的已发送项目中

C++ 简单字符检查