加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 奇怪的可空比较行为

发布时间:2020-12-15 05:40:29 所属栏目:百科 来源:网络整理
导读:以下行为背后的理性(如果有的话)是什么: int? a = null;Console.WriteLine(1 a); // prints FalseConsole.WriteLine(1 = a); // prints FalseConsole.WriteLine(Comparerint?.Default.Compare(1,a)); // prints 1 为什么比较运算符的行为与默认的nullables
以下行为背后的理性(如果有的话)是什么:
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)

解决方法

< =和>如果任一值为null,则提升运算符返回false.

For the relational operators

< > <= >=

a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator produces the value false if one or both operands are null. Otherwise,the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.

由于比较器用于排序,因此它们需要一个总排序,其中null定义比较小于其他每个值.这种需求优先于比较运算符的一致性.将null与任何其他值进行比较时返回0是不可能的,这会违反传递性,因此设计者必须选择发出错误,或者总是将null排序为小于或大于任何其他值.在.net 1中,他们认为null小于引用类型的其他所有内容,并且自然地决定转移到.net 2中的可空值类型.

它们之间的差异非常类似于NaN在浮点上的行为方式.例如,NaN甚至不等于自身,并且所有比较运算符都返回false.但是当使用比较器时,NaN等于它自己并且小于除null之外的其他值.

Enumerable.Min返回最小的非null值,如果序列不包含非null值,则仅返回null.使用这样的函数null通常代表省略的值,并且您有兴趣找到最小的实际值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读