c# - Nullable <= 与 == 比较结果

标签 c# comparison operator-keyword nullable

这种行为对我来说听起来是错误的。

DateTime? birth = null;
DateTime? death = null;

Console.WriteLine(birth == death); // true
Console.WriteLine(birth <= death); // false

为什么会这样呢?这实在是太奇怪了。当然,我的意思是为什么第二个表达式的计算结果不等于 true也是如此。

编辑:

据我了解,以下比较返回 false ,因为无法说出它们之间的关系:

Console.WriteLine(birth < death); // false
Console.WriteLine(birth > death); // false

这是完全可以理解的行为。但是...看看逻辑:

  • <=意味着 <==
  • 我们不知道如何阅读 < - 可能是truefalse
  • 我们确实知道 ==true
  • 因为条件之一是 true ,其他条件不能不真实结果。这是逻辑,而不是

我的观点是 true or something else 应该是真的。

我知道 C# 团队是这样设计的,但我的直觉不同。既然聪明人已经用这样的规则编写了 C#,我只想了解为什么我的直觉在这里是错误的:)

最佳答案

根据 ECMA-334 标准(8.19 Nullable types)(强调我的):

A comparison operator (==, !=, <, >, <=, >=) has a lifted form when the operand types are both non-nullable value types and the result type is bool. The lifted form of a comparison operator is formed by adding a ? modifier to each operand type (but not to the result type). Lifted forms of the == and != operators consider two null values equal, and a null value unequal to a non-null value. Lifted forms of the <, >, <=, and >= operators return false if one or both operands are null.

关于c# - Nullable <= 与 == 比较结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31722024/

相关文章:

c# - WPF 图表工具包 y 轴标签对于小数字显示为零

c# - 递归 Linq - 子属性的父指示?

c# - 更改身份数据库

c# - 一次性对象克隆会导致 C# 中的内存泄漏吗?

c - 搜索 vector 中出现两次的所有整数

ios - 如何转换颜色?

java - 比较 boolean 值

go - 无效操作 : (operator - not defined on string)

c++ - 我的程序因运算符过载而不断出现段错误

c++ - C++中运算符=的继承问题