舉例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | interface Demo { void DoSomething(); int DoSomething2( int a, int b); } class Demo2 : Demo { void Demo.DoSomething() { System.Console.WriteLine( "There is no spoon." ); } int Demo.DoSomething2( int a, int b) { return a + b; } static void Main() { Demo d = new Demo2(); d.DoSomething(); System.Console.WriteLine(d.DoSomething2(2, 3)); } } /* 《程式語言教學誌》的範例程式 檔名:interface.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
此例我們定義一個 Demo 介面,宣告兩個方法
1 2 3 4 | interface Demo { void DoSomething(); int DoSomething2( int a, int b); } |
實作 Demo 介面的為 Demo2 類別,使用跟繼承一樣的冒號 :
6 | class Demo2 : Demo { |
方法實作需要加上介面名稱
7 8 9 10 11 12 13 | void Demo.DoSomething() { System.Console.WriteLine( "There is no spoon." ); } int Demo.DoSomething2( int a, int b) { return a + b; } |
須注意使用介面宣告的方法,物件變數要宣告為介面的型態,然後用實作類別的建構子建立
16 17 18 | Demo d = new Demo2(); d.DoSomething(); System.Console.WriteLine(d.DoSomething2(2, 3)); |
編譯執行,結果如下

中英文術語對照 | |
---|---|
關鍵字 | keyword |
介面 | interface |
方法 | method |
類別 | class |
您可以繼續參考
介面 interface相關目錄
回 C# 快速導覽 回 C# 教材 回首頁參考資料
Standard ECMA-334 C# Language Specification msdn: 介面 (C# 參考)
沒有留言:
張貼留言