C# 使用接口進行排序

 接口的定義是指定一組函數成員而不實現成員的引用類型,其它類型和接口可以繼承接口。定義還是很好理解的,但是沒有反映特點,接口主要有以下特點:

(1)通過接口可以實現多重繼承,C#接口的成員不能有public、protected、internal、private等修飾符。原因很簡單,接口裏面的方法都需要由外面接口實現去實現方法體,那麼其修飾符必然是public。C#接口中的成員默認是public的,java中是可以加public的。

(2)接口成員不能有new、static、abstract、override、virtual修飾符。有一點要注意,當一個接口實現一個接口,這2個接口中有相同的方法時,可用new關鍵字隱藏父接口中的方法。

(3)接口中只包含成員的簽名,接口沒有構造函數,所有不能直接使用new對接口進行實例化。接口中只能包含方法、屬性、事件和索引的組合。接口一旦被實現,實現類必須實現接口中的所有成員,除非實現類本身是抽象類。

(4)C#是單繼承,接口是解決C#裏面類可以同時繼承多個基類的問題。

今天就來說一下如何用接口來進行排序:

有3種方式:

1.使用 IComparer<T>

2.使用IComparable<T>

3.自定義接口實現

這是Student類:

public   class Student:Person,IComparable<Student>,IHomeWorkCollector
    {
        private string hoddy;


        public string Hoddy
        {
            get { return hoddy; }
            set { hoddy = value; }
        }


        public Student()
        {
        }
        public Student(string name,int age,string hoddy):base(name,age)
        {
            this.Hoddy = hoddy;

        }

}



現在說使用IComparer<T>的方法:

定義3個方法:用名字和年齡進行排序

 public class NameComparer : IComparer<Student>
    {
        public int Compare(Student X, Student Y)
        {
            return (X.Name.CompareTo(Y.Name));
        }

    }


    public class NameComparerDesc : IComparer<Student>
    {
        public int Compare(Student X, Student Y)
        {
            return (Y.Name.CompareTo(X.Name));
        }
    }


    public class AgeComParer : IComparer<Student>
    {
        public int Compare(Student X, Student Y)
        {
            return (X.Age.CompareTo(Y.Age));
        }

    }


調用:

使用名字排序:

InitStudents();
            students.Sort (new NameComparer());

            PrintStudents(students);

使用年齡排序:

 InitStudents();
            students.Sort(new AgeComParer());
            PrintStudents(students);


2.使用IComparable<T>:

自己定義一個未實現的接口IComparable

public interface IComparable<in T>
    {

        int CompareTo(T other);

    }

在Students定義他的方法CompareTo:

public int CompareTo(Student other)
        {
            return this.Name.CompareTo(other.Name);

        }

調用Sort方法進行排序

3.使用自定義接口:

自己定義一個接口

 public   interface IHomeWorkCollector
    {
      void CollectHomework();

    }

在學生類中實現:

 public void CollectHomework()
        {
            MessageBox.Show("報告程沐喆!作業收集完畢!");

        }

在教師類中實現:

  public void CollectHomework()
        {
            MessageBox.Show("程沐喆,該交作業了");

        }

進行調用:

 IHomeWorkCollector coll1 = createHomeworkCOllector("student");
            IHomeWorkCollector coll2 = createHomeworkCOllector("teacher");
            coll1.CollectHomework();
            coll2.CollectHomework();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章