What's the Comparer class for?

后端 未结 7 1996
逝去的感伤
逝去的感伤 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

    Because you need sometimes keep sets/ordered queues ordered by something else then 'natural' order or more then one natural order exists.

    For example if you have plane lines you may want to sort it by:

    • Flight number
    • Destination
    • Time
    • Priority (some flights can suffer longer delays then others)
    • ...

    Tasks in computer can be scheduled by:

    • User
    • Priority (in scheduler)
    • PID (normal comparation)
    • ...

    So even in one application you may need to sort the objects by different properties. You cannot do this by int compareTo(Object) method as it cannot differentatie between contexts. However you can add the context i.e. implement CompareByPriority.

提交回复
热议问题