What's the Comparer class for?

后端 未结 7 1997
逝去的感伤
逝去的感伤 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 - 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 where T is comparable, even though Nullable clearly isn't IComparable or IComparable
    • it prevents explosion of generic type constraints by not demanding them - for examle, a List 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

提交回复
热议问题