c# - 比较两个可空值

标签 c# nullable lifted-operators

C# 5.0 规范在第 7.1.3 章中读取

https://msdn.microsoft.com/en-us/library/ms228593.aspx

The lifted operator produces the value false if one or both operands are null.

但是测试以及这个 MSDN 链接

http://msdn.microsoft.com/en-us/library/2cf62fcy(v=vs.100).aspx

int? num1 = 10;
int? num2 = null;

// Change the value of num1, so that both num1 and num2 are null.
num1 = null;
if (num1 == num2)
{
  // The equality comparison returns true when both operands are null.
  Console.WriteLine("num1 == num2 returns true when the value of each is null");
}

/* Output:
 * num1 == num2 returns true when the value of each is null
 */

显示比较两个均为 null 的可空值返回 true

这是有道理的,但它与规范中的句子相矛盾,不是吗?

最佳答案

不要混用,这是关于不同类型的运算符。

• 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.

• For the relational 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 produces the value false if one or both operands are null. Otherwise, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.

关于c# - 比较两个可空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39873967/

相关文章:

android - 如果参数不为 null,我如何告诉 kotlin 函数不返回 null?

c# - 转换十进制?原始十进制

typescript - 为什么不允许对 Typescript 中的数组条目进行空检查?

c# - 将 struct 与 null 进行比较时出现错误的编译器警告

c# - 在一个简单的 Viewbag.Title 中,获取 RuntimeBinderException

c# - C# 中的 fmodf 等效吗?

c# linq 如何检查我需要不为空的同一列中的空值

c# - HasManyToMany Fluent NHibernate 映射删除错误