C# 接口 Interface(學習心得 22)

接口定義了所有類繼承接口時應遵循的語法合同。

接口定義了語法合同 “是什麼” 部分,派生類定義了語法合同 “怎麼做” 部分。

接口定義了屬性、方法和事件,這些都是接口的成員。

接口只包含了成員的聲明。

成員的定義是派生類的責任。

接口提供了派生類應遵循的標準結構。

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

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

一、定義接口: MyInterface.cs

使用 interface 關鍵字聲明,它與類的聲明類似。

接口聲明默認是 public 的。

例:

interface IMyInterface
{
    void MethodToImplement();
}

以上代碼定義了接口 IMyInterface。

通常接口命令以 I 字母開頭。

這個接口只有一個方法 MethodToImplement(),沒有參數和返回值,當然我們可以按照需求設置參數和返回值。

值得注意的是,該方法並沒有具體的實現。

二、接口實現: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.");
    }
}

運行結果:

MethodToImplement() called.

三、接口繼承: InterfaceInheritance.cs

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

例: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.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章