黄色电影一区二区,韩国少妇自慰A片免费看,精品人妻少妇一级毛片免费蜜桃AV按摩师 ,超碰 香蕉

C# 接口 Interface

c# 接口 interface

接口定義了所有類繼承接口時應(yīng)遵循的語法合同。接口定義了語法合同 "是什么" 部分,派生類定義了語法合同 "怎么做" 部分。

接口定義了屬性、方法和事件,這些都是接口的成員。接口只包含了成員的聲明。成員的定義是派生類的責(zé)任。接口提供了派生類應(yīng)遵循的標(biāo)準(zhǔn)結(jié)構(gòu)。

接口使得實(shí)現(xiàn)接口的類或結(jié)構(gòu)在形式上保持一致。

抽象類在某種程度上與接口類似,但是,它們大多只是用在當(dāng)只有少數(shù)方法由基類聲明由派生類實(shí)現(xiàn)時。

接口本身并不實(shí)現(xiàn)任何功能,它只是和聲明實(shí)現(xiàn)該接口的對象訂立一個必須實(shí)現(xiàn)哪些行為的契約。

抽象類不能直接范例化,但允許派生出具體的,具有實(shí)際功能的類。

 

1. 定義接口: myinterface.cs

接口使用 interface 關(guān)鍵字聲明,它與類的聲明類似。接口聲明默認(rèn)是 public 的。下面是一個接口聲明的范例:

interface imyinterface
{
? ? void methodtoimplement();
}

以上代碼定義了接口 imyinterface。通常接口命令以 i 字母開頭,這個接口只有一個方法 methodtoimplement(),沒有參數(shù)和返回值,當(dāng)然我們可以按照需求設(shè)置參數(shù)和返回值。

值得注意的是,該方法并沒有具體的實(shí)現(xiàn)。

接下來我們來實(shí)現(xiàn)以上接口:interfaceimplementer.cs

using system;

interface imyinterface
{
? ? ? ? // 接口成員
? ? void methodtoimplement();
}

class interfaceimplementer : imyinterface
{
? ? static void main()
? ? {
? ? ? ? interfaceimplementer iimp = new interfaceimplementer();
? ? ? ? iimp.methodtoimplement();
? ? }

? ? public void methodtoimplement()
? ? {
? ? ? ? console.writeline("methodtoimplement() called.");
? ? }
}

interfaceimplementer 類實(shí)現(xiàn)了 imyinterface 接口,接口的實(shí)現(xiàn)與類的繼承語法格式類似:

class interfaceimplementer : imyinterface

繼承接口后,我們需要實(shí)現(xiàn)接口的方法 methodtoimplement() , 方法名必須與接口定義的方法名一致。

 

2. 接口繼承: interfaceinheritance.cs

以下范例定義了兩個接口 imyinterface 和 iparentinterface。

如果一個接口繼承其他接口,那么實(shí)現(xiàn)類或結(jié)構(gòu)就需要實(shí)現(xiàn)所有接口的成員。

以下范例 imyinterface 繼承了 iparentinterface 接口,因此接口實(shí)現(xiàn)類必須實(shí)現(xiàn) methodtoimplement() 和 parentinterfacemethod() 方法:

 using system;

interface iparentinterface
{
? ? void parentinterfacemethod();
}

interface imyinterface : iparentinterface
{
? ? void methodtoimplement();
}

class interfaceimplementer : imyinterface
{
? ? static void main()
? ? {
? ? ? ? interfaceimplementer iimp = new interfaceimplementer();
? ? ? ? iimp.methodtoimplement();
? ? ? ? iimp.parentinterfacemethod();
? ? }

? ? public void methodtoimplement()
? ? {
? ? ? ? console.writeline("methodtoimplement() called.");
? ? }

? ? public void parentinterfacemethod()
? ? {
? ? ? ? console.writeline("parentinterfacemethod() called.");
? ? }
}

范例輸出結(jié)果為:

methodtoimplement() called.
parentinterfacemethod() called.

下一節(jié):c# 命名空間 namespace

c# 教程

相關(guān)文章