介面的實現

來源:互聯網
上載者:User

15.4.1 類對介面的實現

前面我們已經說過,介面定義不包括方法的實現部分。介面可以通過類或結構來實現。我們主要講述通過類來實現介面。用類來實現介面時,介面的名稱必須包括在類聲明中的基類列表中。

下面的例子給出了由類來實現介面的例子。其中ISequence為一個隊列介面,提供了向隊列尾部添加對象的成員方法Add(),IRing為一個迴圈表介面,提供了向環中插入對象的方法Insert(object obj),方法返回插入的位置。類RingSquence實現了介面ISequence和介面IRing。

程式清單15-4:

using System;interface ISequence{ object Add();}interface IRing{ int Insert(object obj);}class RingSequence:ISequence,IRing{ public object Add(){...}      public int Insert(object obj){...}}

如果類實現了某個介面,類也隱式地繼承了該介面的所有父介面,不管這些父介面有沒有在類聲明的基類列表中列出。

using System;interface IControl{ void Paint();}interface ITextBox:IControl{ void SetText(string text);}class TextBox:ITextBox{ public void Paint(){...} public void SetText(string text){...}}

這裡,類TextBox不僅實現了介面ITextBox,還實現了介面ITextBox的父介面IControl。

前面我們已經看到,一個類可以實現多個介面。再看下面的例子:

using System;interface IControl{ void Paint();}interface IDataBound{ void Bind(Binder b);}public class Control:IControl{ public void Paint(){...}}public class EditBox:Control,IControl,IDataBound{ public void Paint(){...} public void Bind(Binter b){...}}

上例中,類EditBox從Control類繼承並同時實現了IControl and IDataBound介面。EditBox中的Paint方法來自IControl介面,Bind方法來自IDataBound介面,二者在EditBox類中都作為公有成員實現。當然,在C#中我們也可以選擇不作為公有成員實現介面。

如果每個成員都明顯地指出了被實現的介面,通過這種途徑被實現的介面我們稱之為顯式介面成員(explicit interface member)。用這種方式我們改寫上面的例子:

public class EditBox:IControl,IDataBound{ void IControl.Paint(){...} void IDataBound.Bind(Binder b){...}}顯式介面成員只能通過介面調用。例如:class Test{ static void Main(){    EditBox editbox=new EditBox();    editbox.Paint(); //error:no such method    IControl control=editbox;    control.Paint(); //calls EditBox's Paint implementation }}

上述代碼中對editbox.Paint()的調用是錯誤的,因為editbox本身並沒有提供這一方法。control.Paint()是正確的調用方式。

注意:介面本身不提供所定義的成員的實現,它僅僅說明這些成員,這些成員必須依靠實現介面的類或其它介面的支援。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.