我开始学习可空类型并遇到了以下行为。
在尝试 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,我在这里遗漏了什么吗?
最佳答案
根据 MSDN - 它在“运算符(operator)”部分的页面下方:
When you perform comparisons with nullable types, if the value of one of the nullable types is
null
and the other is not, all comparisons evaluate tofalse
except for!=
所以两者都是a > b
和 a < b
评估为 false
自 a
为空...
关于c# - 比较运算符如何与 null int 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777745/