比较运算符如何使用null int?

我开始学习可空的types,并遇到以下行为。

当尝试可空int,我看比较运算符给我意想不到的结果。 例如,在我的代码下面,我得到的输出是“两者和1是相等的” 。 请注意,它也不打印“null”。

int? a = null; int? b = 1; if (a < b) Console.WriteLine("{0} is bigger than {1}", b, a); else if (a > b) Console.WriteLine("{0} is bigger than {1}", a, b); else Console.WriteLine("both {0} and {1} are equal", a, b); 

我希望任何非负整数将大于空,我在这里失踪的东西?

根据MSDN – 它是在“运营商”部分的页面:

当您使用可为空的types执行比较时,如果其中一个可为空的types的值为null而另一个不为null ,则所有比较都计算为false除了!=

所以a > ba < b a都是false因为a是空的。

正如MSDN所说的

当您使用可为空的types执行比较时,如果其中一个可为空的types的值为空而另一个不是,则除了!=(不等于)之外,所有比较都计算为false。 重要的是不要假设,因为一个特定的比较返回false,相反的情况下返回true。 在以下示例中,10不大于,小于或等于null。 只有num1!= num2的计算结果为true。

 int? num1 = 10; int? num2 = null; if (num1 >= num2) { Console.WriteLine("num1 is greater than or equal to num2"); } else { // This clause is selected, but num1 is not less than num2. Console.WriteLine("num1 >= num2 returned false (but num1 < num2 also is false)"); } if (num1 < num2) { Console.WriteLine("num1 is less than num2"); } else { // The else clause is selected again, but num1 is not greater than // or equal to num2. Console.WriteLine("num1 < num2 returned false (but num1 >= num2 also is false)"); } if (num1 != num2) { // This comparison is true, num1 and num2 are not equal. Console.WriteLine("Finally, num1 != num2 returns true!"); } // 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 returned false (but num1 < num2 also is false) * num1 < num2 returned false (but num1 >= num2 also is false) * Finally, num1 != num2 returns true! * num1 == num2 returns true when the value of each is null */ 

总而言之,即使两个操作数都为null,任何与null( >=<<=> )的不等式比较都将返回false 。 即

 null > anyValue //false null <= null //false 

任何与null( ==!= )的相等或不相等比较的工作“按预期”工作。 即

 null == null //true null != null //false null == nonNull //false null != nonNull //true