What's the Comparer class for?

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

    The type doesn't need to implement IComparable, it can be any type - there are no constrains on T:

    public abstract class Comparer : IComparer, IComparer
    

    The new Comparer you create implements IComparer and the non-generic IComparer, and can be used for comparisons and sorting of collections.

    You are correct: if your type, Customer implements IComparable, and you don't need another comparison, Comparer isn't useful to you. Most classes in the .net framework can accept both IComparable or Comparer, so you can use either one.

    However, you are wrong to assume that is always the case. It is very possible to create a Comparer for a non-Comparable type. Note that the following is not required:

    public abstract class Comparer : IComparer, IComparer
                                        where T : IComparable, IComparable
    

    Suppose you have a simple class, Person and you want to sort a list of Persons, your best bet it to write a Comparer:

    public class Person
    {
        string Name { get; set; }
    }
    

提交回复
热议问题