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

标签 c# nullable

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

在尝试 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 to false except for !=

所以两者都是a > ba < b评估为 falsea为空...

关于c# - 比较运算符如何与 null int 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777745/

相关文章:

c# - 如何将 Entity Framework 4.5 设置为从不将任何属性设置为 Nullable

c# - 实现(绘制)3d 图/散点图的最简单方法是什么,相当于来自 matlab 的 plot3?

c# - 小方法的函数调用是否会消耗内存.....在C#中

c# - 我怎么能在int上执行方法?在没有 NullReferenceException 的情况下设置为 null?

c# - 可空泛型扩展方法

types - 有没有一种很好的方法可以在 Go 中模拟 "Maybe"或 "option"类型?

c# - 在C#中记录登录、注销、系统锁定/解锁事件

c# - 使用 TextWriter c# 清除文本文件的内容

c# - 抛出System.OutOfMemoryException'-WebClient.DownloadStringAsynch()

c# - 取两个可为空的值中的较大者