通過實現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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM