确保使用有效的IComparer

时间:2017-01-20 06:13:36

标签: c# generics .net-core icomparer

我有一个类(Foo),它需要比较T类型的对象,但T可能并不总是实现IComparable,构造函数应该能够与null一起使用comparer param。为了在创建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. ");

    }
}

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

我该如何应对这种情况?

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

1 个答案:

答案 0 :(得分:1)

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

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;


}