泛型接口IComparable<T>及IComparer<T>使用

    IComparable<T>是IComparable接口的泛型版本,对比较对象的类型做出了约束。使用方法如下:

(1)定义类实现接口,如 public class Student:IComparable<Student>

(2)实现接口中的泛型方法CompareTo(T t),如

        public Int32 CompareTo(Student other)
        {
            return this.Age.CompareTo(other.Age);
        }

(3)可以对加入泛型集合中的对象进行默认排序

            List<Student> students = new List<Student>();
            Student s1 = new Student("b", 20, Genders.Male);
            Student s2 = new Student("a", 18, Genders.Male);

            students.Sort();

 如果想在排序时指定排序方式,则可调用Sort方法的重载方法Sort(IComparer<T> comparer)。使用方法如下:

(1)定义类实现接口,如public class NameCompare : IComparer<Student>

(2)实现接口中的泛型方法int Compare(T x,T y),如

        public int Compare(Student x, Student y)
        {
          return x.Name.CompareTo(y.Name);
        }

(3)可以对加入泛型集合中的对象按指定方式进行排序

    students.Sort(new NameCompare());

原文地址:https://www.cnblogs.com/zhouhb/p/2033455.html