通过实现System.IComparable接口的CompareTo方法对两个类进行比较

假设现在有一个学生类

 class Student 
    {
        int age;
        public Student(int age)
        {
            this.age = age;
        }
   }

要使学生类之间能进行比较,实现System.IComparable接口的CompareTo方法

 class Student : System.IComparable
    {
        int age;
        public Student(int age)
        {
            this.age = age;
        }
 public int CompareTo(object obj)
        {
            Student stu = (Student)obj;
            if (this.age > stu.age)
                return 1;
            else if (this.age == stu.age)
                return 0;
            else
                return -1;
        }
    }

这样即可以比较两个类

1             Student xiaomin = new Student(20);
2             Student xiaohong = new Student(15);
3             if (xiaomin.CompareTo(xiaohong) > 0)
4                 Console.WriteLine("小明比小红大");
5             else
6                 Console.WriteLine("小明不比小红大");        

研究一下System.IComparable接口,就会发现它的参数被定义成一个object。
然而这种方式不是类型安全的,
因为可能传进去的不是Student类型,就出报错
为了确保类型安全,应使用System.命名空间中定义的泛型
IComparable<T>接口,它定义了以下方法:
int CompareTo(T other);
方法获取的是类型参数T,而不是object, 所有安全得多

 1 class Student : System.IComparable<Student>
 2     {
 3         int age;
 4         public Student(int age)
 5         {
 6             this.age = age;
 7         }
 8 
 9      public int CompareTo(Student stu)
10         {
11             if (this.age > stu.age)
12                 return 1;
13             else if (this.age == stu.age)
14                 return 0;
15             else
16                 return -1;
17         }
18 }
原文地址:https://www.cnblogs.com/zhaotianff/p/6004528.html