确保使用有效的 IComparer

Ensuring a valid IComparer is being used

我有一个 class (Foo) 需要比较 T 类型的对象,但是 T 可能并不总是实现 IComparable 并且构造函数应该能够与 null comparer 参数一起使用。为了在创建 Foo 时捕捉到这一点,我尝试了以下操作:

public sealed class Foo<T>
{

    private readonly IComparer<T> _comparer;

    public Foo(IComparer<T> comparer)
    {
        _comparer = comparer ?? Comparer<T>.Default;
        if (_comparer == null)
            throw new NotSupportedException("A comparer was not passed for T and no default was found for T. ");

    }
}

我假设(错误地)如果对象没有实现 IComparable<T> Comparer<T>.Default 将为 null 但 Default 仍然 return 一个有效的 Comparer 在调用比较时会抛出一个 ArgumentsException,我无法通过研究如何处理这种情况找到解决方案。

我应该如何处理这种情况?

编辑:澄清一下 class 应该能够使用给定的比较器对类型 T 的对象进行排序。但是 T 可能并不总是具有 IComparable,但是当提供 Comparer 时,它仍然应该能够对那些约束会破坏该要求的对象进行排序。但是,如果传入的 Comparer 为 null,那么它应该尝试使用 Default,如果对象是 IComparable,则一切正常,否则它应该抛出一个 NotSupportedException.

根据你更新的问题,我会给出新的答案。

public Foo(IComparer<T> comparer)
{
    _comparer = comparer ?? 
                     typeof(IComparable<T>).IsAssignableFrom(typeof(T)) 
                     ? Comparer<T>.Default : null;
    if (_comparer == null)
        throw new NotSupportedException("A comparer was not passed for T and no default was found for T. ");

}

我怎么不喜欢线性解决方案。以下看起来更干净 IMO

public Foo(IComparer<T> comparer)
{
    if(comparer == null)
    {
        if(typeof(IComparable<T>).IsAssignableFrom(typeof(T))
        {
             comparer = Comparer<T>.Default;
        }
        else 
             throw new NotSupportedException("A comparer was not passed for T and no default was found for T. ");
    }

    _comparer = comparer;


}