C# 接口(Interface)理解

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

接口定義了屬性、方法和事件,這些都是接口的成員。接口只包含了成員的聲明。成員的定義是派生類的責任。接口提供了派生類應遵循的標準結構。

接口使得實現接口的類或結構在形式上保持一致。

抽象類在某種程度上與接口類似,但是,它們大多隻是用在當只有少數方法由基類聲明由派生類實現時。


接口使用 interface 關鍵字聲明,它與類的聲明類似。接口聲明默認是 public 的。接口的方法並沒有具體的實現。

接下來我們來實現以上接口: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 類實現了 IMyInterface 接口,接口的實現與類的繼承語法格式類似。

繼承接口後,我們需要實現接口的方法 MethodToImplement() , 方法名必須與接口定義的方法名一致。


接口繼承: InterfaceInheritance.cs

以下實例定義了兩個接口 IMyInterface 和 IParentInterface。

如果一個接口繼承其他接口,那麼實現類或結構就需要實現所有接口的成員。

以下實例 IMyInterface 繼承了 IParentInterface 接口,因此接口實現類必須實現 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.");
    }
}

實例輸出結果爲:

MethodToImplement() called.
ParentInterfaceMethod() called.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章