What's the Comparer class for?

后端 未结 7 2016
逝去的感伤
逝去的感伤 2021-02-07 00:02

What purpose does the Comparer class serve if the type that you specify already implements IComparable?

If I specify Comparer.Defaul

相关标签:
7条回答
  • 2021-02-07 00:43

    There are a few subtle points here:

    • it doesn't just support IComparable<T> - it also supports the older (non-generic) IComparable as a fallback. This means that it can't be expressed just as (for example) a generic constraint
    • it supports Nullable<T> where T is comparable, even though Nullable<T> clearly isn't IComparable or IComparable<T>
    • it prevents explosion of generic type constraints by not demanding them - for examle, a List<T> can provide a Sort even though it doesn't insist that all T are sortable; you'd be amazed how quickly the generic constraints would otherwise accumulate
    • it allows you to pass a comparer into any of the existing APIs that demand a comparer, when all you have is a type that may be comparable; most of the framework sorting APIs (including LINQ) will offer comparer support
    0 讨论(0)
提交回复
热议问题