为什么 Nullable<T> 不实现 IComparable?

Why doesn't Nullable<T> implement IComparable?

这个问题的答案可能是显而易见的,但无论如何我还是要问问。

我正在写一个 Range<T> class,在这个过程中我意识到我需要一个比较器。所以,我写了一个通用的比较器,自然地从 Comparer<T>:

派生
public class Range<T> where T : IComparable
{

    // Simplified here for brevity -- actually uses the comparer
    public T Min { get; set; }

    // Simplified here for brevity -- actually uses the comparer
    public T Max { get; set; }

    private class DefaultComparer : Comparer<T> 
    {
        public override int Compare(T x, T y)
        {
            return x == null && y == null 
                ? 0 
                : x == null 
                    ? -1 
                    : y == null 
                        ? 1 
                        : x.CompareTo(y);
        }
    }
}

现在,这一切都很好,直到您将 Nullable<T> 作为类型传递。例如:

public Range<DateTime?> DateSentFilter { get; set; }

这很糟糕,因为,当然,Nullable<T> 没有实现 IComparable。这让我开始思考:为什么不呢?

鉴于通常如何编写比较器,为什么不能呢?

有没有对这东西有深入了解的人知道?是否存在禁止这样做的情况?

嗯,提供给 Nullable<T> 的通用类型不需要实现 IComparable 本身。

您自己提供了这个条件:T : IComparable,但Nullable<T>中的T不一定成立。我同意 Nullable<T> 通常用于实现 IComparable 的原始类型,但您可以在结构上使用它,并且它们没有实现 IComparable

这是来自 source code 的评论:

// Warning, don't put System.Runtime.Serialization.On*Serializ*Attribute
// on this class without first fixing ObjectClone::InvokeVtsCallbacks
// Also, because we have special type system support that says a a boxed Nullable<T>
// can be used where a boxed<T> is use, Nullable<T> can not implement any intefaces
// at all (since T may not).   Do NOT add any interfaces to Nullable!
// 

如其所说,Nullable<T> 由于给定原因无法实现任何接口。

现在,第二个问题是:如果可以,他们会实施 IComparable 吗? 不会。Patrick 已经说明了原因。并非每个 T 都实现 IComparable,这没有意义。