这种行为对我来说听起来是错误的。
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
这是完全可以理解的行为。但是...看看逻辑:
-
<=
意味着<
或==
- 我们不知道如何阅读
<
- 可能是true
或false
- 我们确实知道
==
是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 isbool
. 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/