中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

C# 接口(Interface)

接口定義了所有類繼承接口時(shí)應(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í)。


定義接口: MyInterface.cs

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

interface IMyInterface
{
? ? void MethodToImplement();
}

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

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

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

實(shí)例

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() , 方法名必須與接口定義的方法名一致。


接口繼承: InterfaceInheritance.cs

以下實(shí)例定義了兩個(gè)接口 IMyInterface 和 IParentInterface。

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

以下實(shí)例 IMyInterface 繼承了 IParentInterface 接口,因此接口實(shí)現(xiàn)類必須實(shí)現(xiàn) MethodToImplement() 和 ParentInterfaceMethod() 方法:

實(shí)例

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.");
? ? }
}

實(shí)例輸出結(jié)果為:

MethodToImplement() called.
ParentInterfaceMethod() called.