When to use IComparable Vs. IComparer

前端 未结 8 1278
[愿得一人]
[愿得一人] 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:54

    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.

提交回复
热议问题