gpt4 book ai didi

c# - 覆盖 CompareTo : What to do with null case?

转载 作者:IT王子 更新时间:2023-10-29 04:42:19 25 4
gpt4 key购买 nike

当给定对象为 null 时,CompareTo 方法应该返回什么?

MSDN Library显示了返回 1 的示例。但我本以为会抛出错误,因为无法与 null 进行比较。

我希望对这个答案有不同的看法。什么是最佳实践方法?

最佳答案

是的,有一个最佳实践。与其他答案所说的相反,有一个预期的标准,而不仅仅是最受欢迎的行为。

IComparable<T>.CompareTo 的 MSDN 文档中给出了正确答案和 IComparable.CompareTo :

By definition, any object compares greater than null, and two null references compare equal to each other.

(根据契约(Contract),比较更大的定义为:if a > b then a.CompareTo(b) > 0 。)

例如 Nullable.Compare<T> 中也证实了这种预期行为. Null 总是比较小于一个值。

还值得注意的是,对于非泛型比较,不匹配的类型不应被视为空值:

The parameter, obj, must be the same type as the class or value type that implements this interface; otherwise, an ArgumentException is thrown.


这不会影响您的问题,但请注意, Nullable<T> comparison operators ( == , != , < , <= , > , >= )不遵循 IComparable约定

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 != (not equal). It is important not to assume that because a particular comparison returns false, the opposite case returns true. In the following example, 10 is not greater than, less than, nor equal to null. Only num1 != num2 evaluates to true.

还有一个奇怪的结果是(int?)null == (int?)null计算结果为 true 但 (int?)null <= (int?)null没有。

关于c# - 覆盖 CompareTo : What to do with null case?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17025900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com