When to use IComparable Vs. IComparer

前端 未结 8 1277
[愿得一人]
[愿得一人] 2020-11-29 16:07

I\'m trying to figure out which of these interfaces I need to implement. They both essentially do the same thing. When would I use one over the other?

8条回答
  •  情歌与酒
    2020-11-29 16:55

    Simple Explanation via a story

    High school basketball. It's a school yard pick for the teams. I want to get the tallest/best/fastest folks on my team. What do I do?

    IComparer Interface - Compare two people separate people

    • This allows me to compare any two guys lined up.........that's basically it. Fred vs John..........i throw them into a concrete class which implements the interface. Compare(Fred, John) and it spits out who's better.

    What about IComparable? - Compare yourself with someone else

    Have you been on FB recently? You see other folks doing cool things: travelling the world, creating inventions, while I'm doing something not quite as cool - well what we are doing is making use of the IComparable interface.

    • We are comparing the current instance (yourself) with another object (someone else) which is of the same type (person).

    What about the Comparer Class?

    The Comparer class is an abstract base class which implements the IComparer interface. You should derive from this class to have a concrete implementation. anyways, Microsoft recommends that you DO use the Comparer class rather than implement the IComparer interface:

    We recommend that you derive from the Comparer class instead of implementing the IComparer interface, because the Comparer class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object.

    Summary

    • IComparer - line up two things and compare.
    • IComparable - compare yourself with others on FB.

    Hope the stories help you remember.

提交回复
热议问题