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?
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
- Should I use static function in c# where many call
As others have said, they don't do the same thing.
In any case, these days I tend not to use IComparer. Why would I? Its responsibility (an external entity used to compare two objects) can be handled much cleaner with a lambda expression, similar to how most of LINQ's methods work. Write a quick lambda which takes the objects to compare as arguments, and returns a bool. And if the object defines its own intrinsic compare operation, it can implement IComparable instead.
It depends on the entity. For example following for a class like "Student", it will make sense to have IComparable based on Name.
But if a teacher 'A' wants to compare students based on MathScore, and teacher 'B' wants to compare students based on EnglishScore. It will be good idea to implement IComparer separately. (More like a strategy pattern)