淺析c# 接口
接口:
是指定一組函數成員而不是實現他們的引用類型。所以只能類喝啊結構來實現接口,在結成該接口的類里面必須要實現接口的所有方法
接口的特點:
繼承于接口的類,必須要實現所有的接口成員
類可以繼承,但是類只能繼承一個基類,但是類可以繼承多個接口
接口接口的定義用interface關鍵字,后面加接口的名稱,名稱通常是以字母I開頭,接口不需要訪問修符,因為接口都是供外部調用的,所以都是public的接口定義了所有類集成接口時應該應該遵循的語法合同,接口里面的內容是語法合同中“是什么”的部分,繼承與接口的派生類中定義的是語法合同中“怎么做”的部分,接口中,只定義接口成員的聲明,成員包括屬性、方法、事件等。
因此在定義接口時候要注意如下幾點:
- 1,接口聲明不能包含以下成員:數據成員,靜態(tài)成員
- 2,接口聲明只能包含如下類型的非靜態(tài)成員函數的聲明:方法、屬性、事件、索引器。
- 3,這些函數成員的聲明不能包含任何實現代碼,而且在每一個成員聲明的主題后必須使用分號。
1,例子;
//定義一個接口IParentInterface
interface IParentInterface {
void ParentInterface();//聲明接口成員
}
class AllInterface : IParentInterface
{
public void ParentInterface() {
Console.WriteLine("Hello");
}
}
static void Main(string[] args)
{
AllInterface all = new AllInterface();
all.ParentInterface();
}
實現結果:

2,如果一個接口繼承其他接口,那么實現類或結構就需要實現所有接口的成員
//定義一個接口IParentInterface
interface IParentInterface {
void ParentInterface();//聲明接口成員
}
//IChildInterface
interface IChildInterface {
void ChildInterface();//聲明接口成員
}
class AllInterface : IChildInterface
{
public void ParentInterface() {
Console.Write("Hello" + " ");
}
public void ChildInterface() {
Console.WriteLine("World");
}
}
static void Main(string[] args)
{
AllInterface all = new AllInterface();
all.ParentInterface();
all.ChildInterface();
}
實現結果:

以上就是淺析c# 接口的詳細內容,更多關于c# 接口的資料請關注腳本之家其它相關文章!
相關文章
Visual C#中如何使用IComparable和IComparer接口
這篇文章主要介紹了C#中使用IComparable和IComparer接口,在本例中,該對象被用作第二個參數被傳遞給Array.Sort的接受IComparer實例的重載方法,需要的朋友可以參考下2023-04-04

