C# interface學習經驗淺談
C# interface是把所需成員組合起來,以封裝一定功能的集合。它好比一個模板,在其中定義了對象必須實現的成員,通過類或結構來實現它。接口不能直接實例化,即ICount ic=new iCount()是錯的。接口不能包含成員的任何代碼,只定義成員本身。接口成員的具體代碼由實現接口的類提供。接口使用interface關鍵字進行聲明。聲明格式如下:
- [attributes] [modifiers]
- interface identifier
- [: base-list] {interface-body} {;}
C# interface成員的默認訪問方式是public,在聲明接口成員時不能出現abstract、public、protected、internal、private、virtual、override或static等關鍵字。接口成員可以是方法、屬性、索引指示器或事件,不能是字段,而且接口的成員名不能相同。
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Interface
- {
- interface ICount
- {
- void Count();//接口成員的默認訪問方式是public
- //int number;//接口中不能定義字段成員
- int para { get;set;}
- }
- class Double : ICount
- {
- public void Count()
- { //實現ICount的Count()方法
- Console.WriteLine("The double para is {0}",2*para);
- }
- int p;
- public int para
- {
- get { return p; }
- set { p = value; }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Double d = new Double();
- d.para = 10;//給"屬性"賦值
- d.Count();
- ICount ic = (ICount)d;//轉換為接口
- ic.para = 5;
- ic.Count();
- Console.ReadLine();
- }
- }
- }
C# interface的一點使用總結
1 一個類可以實現一個以上的接口;
2 類必須實現接口中的“所有”屬性和方法;
3 屬性和方法定義所采用的格式必須與接口定義所采用的格式完全相同。方法所采用的參數數目及參數類型必須與接口中的完全相同。方法的名稱也必須相同。
接口之間的繼承:接口的繼承僅僅說明了接口之間的繼承關系,派生的接口繼承了父接口的成員說明,沒有繼承父接口的實現。private和internal類型的接口不允許繼承。如果派生接口中準備重寫父接口的方法,實現方式同類的繼承成員的覆蓋。
如果一個類實現了某個接口,即使父接口沒有在類的基類表中列出,這個類也隱式地繼承了接口的所有父接口。
如果兩個接口A和B含有同名的成員Method,且都由同一個類C實現,則類C必須分別為A和B的Method成員提供單獨的實現,即顯式實現接口成員。可行方案:
(1)直接實現一個接口的成員,顯式實現另一個接口的成員;
(2)顯式實現兩個接口的成員
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Interface
- {
- interface IEnglish
- {
- float Length();
- float Width();
- }
- interface IMetric
- {
- float Length();
- float Width();
- }
- class Class1 : IEnglish, IMetric
- {
- float lengthInches;
- float widthInches;
- public Class1(float length, float width)
- {
- lengthInches = length;
- widthInches = width;
- }
- //顯式實現IEnglish的成員
- float IEnglish.Length()
- {
- return lengthInches;
- }
- float IEnglish.Width()
- {
- return widthInches;
- }
- //顯式實現IMetric的成員
- float IMetric.Length()
- {
- return lengthInches * 2.54f;
- }
- float IMetric.Width()
- {
- return widthInches * 2.54f;
- }
- static void Main(string[] args)
- {
- Class1 c1 = new Class1(30.0f,20.0f);
- IEnglish e=(IEnglish)c1;
- IMetric m=(IMetric )c1;
- Console.WriteLine("Length(in):{0}",e.Length());
- Console.WriteLine("Width(in):{0}",e.Width());
- Console.WriteLine("Length(cm):{0}",m.Length());
- Console.WriteLine("Width(cm):{0}",m.Width());
- Console.ReadLine();
- }
- }
- }
執行結果:
C# interface學習的一些體會和具體的實例演示就向你介紹到這里,希望對你了解和學習C# interface有所幫助。
【編輯推薦】