问题
What is the best practice in C# starting from version 4.0 when writing a comparer class :
a. Should we inherit from Comparer abstract class ? or
b. Should we implement IComparer interface.
What are the pros and cons?
回答1:
I would recommend that you extend the Comparer<T>
class instead of implementing the IComparer<T>
interface, as does Microsoft (see first reference below).
Now, if you want your object itself (whatever T is) to be able to compare against itself, it can implement the IComparable
interface (see second reference below).
From: http://msdn.microsoft.com/en-us/library/8ehhxeaf(v=vs.110).aspx (IComparer<T>
)
We recommend that you derive from the Comparer<T> class instead of implementing the IComparer interface, because the Comparer<T> class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object.
From: http://msdn.microsoft.com/en-us/library/cfttsh47(v=vs.110).aspx (Comparer<T>
)
Derive from this class to provide a custom implementation of the IComparer<T> interface for use with collection classes such as the SortedList<TKey, TValue> and SortedDictionary<TKey, TValue> generic classes. The difference between deriving from the Comparer class and implementing the System.IComparable interface is as follows:
- To specify how two objects should be compared by default, implement the System.IComparable interface in your class. This ensures that sort operations will use the default comparison code that you provided.
- To define a comparer to use instead of the default comparer, derive from the Comparer class. You can then use this comparer in sort operations that take a comparer as a parameter.
回答2:
From this article on MSDN:
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.
来源:https://stackoverflow.com/questions/26698497/should-we-extend-comparert-or-implement-icomparert