What's the Comparer class for?

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

    I think your question is why have a base class that only seems to have one useful method which happens to be the same method you'd implement if you implemented the interface directly. If I understood that correctly I guess you're right that there's not much benefit to deriving from Comparer as opposed to implementing IComparer directly except that the base class provides you with a generic and non-generic implementation with a single overridden method.

    But if your question is why have both IComparer and IComparable, then as others have indicated, Comparer allows you to define different ways to perform the comparison. It is an implementation of the Strategy design pattern. A great example of this would be the various StringComparer properties such as StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase, etc. This allows you to sort strings differently under different circumstances which the IComparable interface simply cannot anticipate.

    But in addition to being able to re-define the way a comparison is performed, sometimes providing an external comparer is the only way you can do it. For example, the Windows Forms ListView class allows you to specify an IComparer for its sort logic. But ListViewItem does not implement IComparable. So without a comparer strategy that knows how to do it, ListViewItem is not sortable because it has no default IComparable implementation.

    So at the end of the day, it's just another extensibility point that allows you more flexibility when you're not the author of the type that is to be sorted (or you need multiple sorting strategies.)


    EDIT: In response to your comment below: "if I have a class that implements IComparer (my own class), this would allow me to sort on any number of properties (a custom sort), why then would I bother using Comparer.Default"

    Perhaps an example would help. Let's say you're writing an extension method that checks to see if a given value is between a range.

    public static bool Between(this T value, T minValue, T maxValue) {
    
        var comparer = Comparer.Default;
    
        int c1 = comparer.Compare(value, minValue);
        int c2 = comparer.Compare(value, maxValue);
    
        return (c1 >= 0 && c2 <= 0);
    
    }
    

    In this case, I don't know anything about the type T. It may implement IComparable or it may implement IComparable or it may implement neither and an exception will be thrown. This also allows me to easily add an overload for this method that lets the caller pass in their own comparer. But Comparer comes in handy here because it lets me get a default comparer for an unknown type that may or may not implement a generic or non-generic IComparable interface.

提交回复
热议问题