C# 使用介面進行排序

來源:互聯網
上載者:User

標籤:ESS   cte   set   組合   教師   abs   pre   public   prot   

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

(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();

C# 使用介面進行排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.