183

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

在尝试 nullable int 时,我看到比较运算符给了我意想不到的结果。例如,在我下面的代码中,我得到的输出是"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,我在这里遗漏了什么吗?

4

4 回答 4

258

根据MSDN - 它位于“运营商”部分的页面下方:

当您对可空类型执行比较时,如果可空类型之一的值是null而另一个不是,则所有比较的计算结果false都为!=

所以两者都a > ba < b评估到false因为a是空的......

于 2013-04-03T02:16:48.580 回答
55

正如 MSDN 所说

当您对可空类型执行比较时,如果其中一个可空类型的值为 null 而另一个不是,则所有比较的结果都为 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
 */
于 2013-04-03T02:20:46.747 回答
37

总结一下:任何与 null ( >=, <, <=, >) 的不等式比较都会返回,false即使两个操作数都为 null。IE

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

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

null == null     //true
null != null     //false
null == nonNull  //false
null != nonNull  //true
于 2016-12-09T01:09:24.213 回答
3

比较 C# 和 SQL

C#:a=null 和 b=null => a==b => true

SQL:a=null 和 b=null => a==b => false

于 2019-09-06T06:08:57.937 回答