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


151

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

在尝试可为空的int时,我看到比较运算符给了我意外的结果。例如,在下面的代码中,我得到的输出是“ 1和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);

我希望任何非负整数都将大于null,我在这里遗漏了什么吗?


5
这是一个小型的.NET Fiddle,可查看几种情况。
Uwe Keim

Answers:


207

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

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

因此,无论a > ba < b评估,以falsea为空...


2
在我的项目中,我目前正在使用VB.NET,似乎在VB中使用nothing <> 1= null,而在C#中使用null != 1= true-我一直在使用LinqPad来测试语句
Luke T O'Brien

2
我只是想知道,并且Lifted Operators在C#stackoverflow.com/questions/3370110/what - are - lifted -operators中值得一提-我想知道这是否可能是VB.NET返回不同结果的原因
Luke T O'Brien

44

正如MSDN所说

当您对可为空的类型执行比较时,如果其中一个可为空的类型的值是null而另一个不是,则所有比较的结果都为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
 */

25

总结:与空任何不平等的比较(>=<<=>)返回false即使两个操作数都为空。即

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

任何具有null(==!=)的相等或不相等比较均“按预期”进行。即

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

它是两者相同int? nonNullint notNull
КоеКто

1
@КоеКто,的行为相同Nullable<NumberTypes> = null。已验证。
阿特鲁

2

比较C#和SQL

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.