【发布时间】:2013-07-14 23:59:18
【问题描述】:
以下行为背后的理性(如果有的话)是什么:
int? a = null;
Console.WriteLine(1 > a); // prints False
Console.WriteLine(1 <= a); // prints False
Console.WriteLine(Comparer<int?>.Default.Compare(1, a)); // prints 1
为什么比较运算符的行为与 nullables 的默认比较器不同?
更多怪事:
var myList = new List<int?> { 1, 2, 3, default(int?), -1 };
Console.WriteLine(myList.Min()); // prints -1 (consistent with the operators)
Console.WriteLine(myList.OrderBy(i => i).First()); // prints null (nothing) (consistent with the comparator)
Console.WriteLine(new int?[0].Min()); // prints null (nothing)
Console.WriteLine(new int[0].Min()); // throws exception (sequence contains no elements)
【问题讨论】:
-
你的问题有问题。 Comparer
.Default.Compare(1, a) 无法返回 True,因为它是 Integer -
@AndréPena:好电话。我已经修复了评论
-
好问题。我一直想写这篇博客。
标签: c# linq nullable comparator