Featured image of post C♯ - 自訂類型(Custom types) - 介面(Interface) 筆記

C♯ - 自訂類型(Custom types) - 介面(Interface) 筆記

介面(Interface) 筆記

可以先看一小山的C#教學,裡面有講得非常仔細,介面 Interface 類似 繼承 Inheritance 使用到的 virtualoverride

(圖片引用:小山的C#教學)

定義好原先的 Class 繼承使用後,有些角色會有的共同的 Method 會使用 Interface 去擴展使用,而 Interface 裡頭的 Method 定義方式 類似於 abstract Method 的方式 定義在 Interface 中 Example:

// IAttackable.cs
Interface IAttackable
{
    void attack(Creature target);
}
// Player.cs
class Player : Creature, IAttackable
{
    public void attack(Creature target) {
        target.injured(30)
    }
}
  • Interface像是契約,要求指定的 Class 使用其能力。
  • 命名的習慣使用 I 為大寫。
  • Interface 和 繼承使用不同, 一個Class可以有多個 Interface。
  • Interface 的 Method 不可以是 Static。
  • Interface 的 Method 一定是 Public。
  • 繼承 base Class 的 Class 也能實作相同的 Interface。
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus