標籤: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# 使用介面進行排序