为什么 ValueTuple 使用非标准的 IComparable 实现?

Why does ValueTuple use non-standard IComparable implementation?

ValueTuple.IComparable.CompareTo(Object) 的文档说 returns:

0 if other is a ValueTuple instance; otherwise, 1 if other is null.

这使得 IComparable 实现看起来毫无用处,除了可能不会破坏可能期望实现接口的代码。较旧的参考 Tuple class 确实遵循标准实现(尽管它可能仅在项目支持 IComparable 时才有效)。

文档说IComparable表示类型可以排序,ValueTuple不是这样:

This interface is implemented by types whose values can be ordered or sorted. It requires that implementing types define a single method, CompareTo, that indicates whether the position of the current instance in the sort order is before, after, or the same as a second object of the same type. (...)

The implementation of the CompareTo method must return an Int32 that has one of three values, as shown in the following table.

Less than zero The current instance precedes the object specified by the CompareTo method in the sort order.

Zero This current instance occurs in the same position in the sort order as the object specified by the CompareTo method.

Greater than zero This current instance follows the object specified by the CompareTo method in the sort order.

所以我的问题是:

非泛型 ValueTuple 表示一个空元组。由于 ValueTuple 是一个结构,这意味着每个 ValueTuple 实例都是相等的,因此不需要对仅包含空 ValueTuple 的集合进行排序。

将 ValueTuple 与 null returns 1 进行比较,原因与将空字符串与 null returns 1 进行比较的原因相同——因为您正在将某物与空进行比较 :)

表示一个或多个元素的元组的 ValueTuple 的通用变体都以您期望的方式实现IComparable.CompareTo()

请注意,元组本身是静态的 class,而它的所有通用变体都表示非空元组。元组仅包含其非空变体的工厂方法。