本篇主要說明接口(interface)的概念與簡單範例的實作。
接口(介面interface):一個可以讀取數據的通訊協議
- 使用關鍵字interface來定義接口
- 接口內定義一組成員,但不實現它們
在接口中的注意項目
- 不能添加訪問修飾符,預設都是隱性public(連public都不用寫)
- 在接口中的方法不能實現(沒有大括號,句尾加;)
- 在接口中定義屬性,屬性也不能實現(類似於自動屬性)
- 一旦某個類實現了接口,就必須實現接口中定義的全部成員,例如接口Food中的Eat()方法
- 不能實例化接口 Food f = new Food();
實現接口
- 實現接口的任何類都必須實現接口內所有的成員(屬性、方法)
- 接口不能直接實例化
- 接口可以包含方法和屬性聲明,不能包含字段
- 接口中所有屬性和方法,預設為public
- 一個子類繼承一個父類的同時,也繼承實現多個接口
範例:
using UnityEngine; using System.Collections; //接口(介面interface):一個可以讀取數據的通訊協議 //1.使用interface關鍵字定義接口(介面) //2.接口定義一組成員,但不直接實現它們 //父類 public class A { } //食物接口 public interface Food { //在接口中定義屬性,屬性也不能實現(類似於自動屬性) float Price { get; } //在接口中定義方法 //1.不能添加訪問修飾符,預設都是隱性public(連public都不用寫) //2.在接口中的方法不能實現(沒有大括號,句尾加;) //吃的方法 void Eat(); } //B接口 public interface B { } //香蕉類 public class Banana : Food { public void Eat() { Debug.Log("吃下香蕉後,HP-10"); } public float Price { get { return 5.6f; } } } //蘋果類 //Apple 繼承於 A類,並實現了 Food 接口 和 B接口 //3.一旦某個類實現了接口,就必須實現接口中定義的全部成員,例如接口Food中的Eat()方法和Price public class Apple : A, Food, B { public void Eat() { Debug.Log("吃下蘋果後,HP+10"); } public float Price { get { return 1.4f; } } } public class CodingTest2 : MonoBehaviour { // Use this for initialization void Start() { //調用方式(1) Apple a = new Apple(); a.Eat(); Debug.Log(a.Price); //調用方式(2)多態 Food b = new Apple(); b.Eat(); Debug.Log(b.Price); //4. 不能實例化接口 Food f = new Food(); Banana banana = new Banana(); banana.Eat(); } // Update is called once per frame void Update() { } }
輸出結果