比较运算符如何处理null int

本文关键字:处理 null int 运算符 何处理 比较 | 更新日期: 2023-09-27 18:07:04

我开始学习可空类型,并遇到以下行为:

当尝试空整型时,我看到比较运算符给了我意想不到的结果。例如,在下面的代码中,我得到的输出是"both and 1 are equal"。注意,它也不会打印"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);

我希望任何非负整数将大于null,我在这里错过了什么?

比较运算符如何处理null int

根据MSDN -它在页面下方的"操作符"部分:

当您与可空类型执行比较时,如果其中一个可空类型的值为null而另一个不是,则除!=外,所有比较的值都为false

所以a > ba < b的值都是false,因为a是空的…

如MSDN所示

当与可空类型进行比较时,如果值为1可空类型的一个为空,另一个为空,所有的比较除!=(不等于)外,求值为false。重要的是不要这样做假设由于某个特定的比较返回false,则相反情况返回true。在下面的例子中,10不是大于、小于、不等于null的。只有num1 != num2

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 (>=, <, <=, >)的不相等比较返回false,即使两个操作数都为空。例如

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

与null (==, !=)的任何相等或非相等比较都可以"按预期"工作。例如

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

比较c#和SQL

c#: a=null and b=null => a==b => true

SQL: = null和b = null => = = b =>假

如果你在最后一个else "else If (a == b)"你根本不会得到任何输出。A不大于1,不小于1或等于1,为空