C#類實(shí)現(xiàn)接口簡(jiǎn)單介紹
本文向大家介紹C#類實(shí)現(xiàn)接口,可能好多人還不知道C#類實(shí)現(xiàn)接口,沒有關(guān)系,看完本文你肯定有不少收獲,希望本文能教會(huì)你更多東西。
C#類實(shí)現(xiàn)接口
前面我們已經(jīng)說過,接口定義不包括方法的實(shí)現(xiàn)部分。接口可以通過類或結(jié)構(gòu)來實(shí)現(xiàn)。我們主要講述通過類來實(shí)現(xiàn)接口。用類來實(shí)現(xiàn)接口時(shí),接口的名稱必須包含在類定義中的基類列表中。
下面的例子給出了C#類實(shí)現(xiàn)接口的例子。其中ISequence 為一個(gè)隊(duì)列接口,提供了向隊(duì)列尾部添加對(duì)象的成員方法Add( ),IRing 為一個(gè)循環(huán)表接口,提供了向環(huán)中插入對(duì)象的方法Insert(object obj),方法返回插入的位置。類RingSquence 實(shí)現(xiàn)了接口ISequence 和接口IRing。
- using System ;
- interface ISequence {
- object Add( ) ;
- }
- interface ISequence {
- object Add( ) ;
- }
- interface IRing {
- int Insert(object obj) ;
- }
- class RingSequence: ISequence, IRing
- {
- public object Add( ) {…}
- public int Insert(object obj) {…}
- }
如果類實(shí)現(xiàn)了某個(gè)接口,類也隱式地繼承了該接口的所有父接口,不管這些父接口有沒有在類定義的基類表中列出??聪旅娴睦樱?/P>
- using System ;
- interface IControl {
- void Paint( );
- }
- interface ITextBox: IControl {
- void SetText(string text);
- }
- interface IListBox: IControl {
- void SetItems(string[] items);
- }
- interface IComboBox: ITextBox, IListBox { }
這里, 接口IcomboBox繼承了ItextBox和IlistBox。類TextBox不僅實(shí)現(xiàn)了接口ITextBox,還實(shí)現(xiàn)了接口ITextBox 的父接口IControl。
前面我們已經(jīng)看到,一個(gè)類可以實(shí)現(xiàn)多個(gè)接口。再看下面的例子:
- interface IDataBound {
- void Bind(Binder b);
- }
- public class EditBox: Control, IControl, IDataBound {
- public void Paint( );
- public void Bind(Binder b) {...}
- }
類EditBox從類Control中派生并且實(shí)現(xiàn)了Icontrol和IdataBound。在前面的例子中接口Icontrol中的Paint方法和IdataBound接口中的Bind方法都用類EditBox中的公共成員實(shí)現(xiàn)。C#提供一種實(shí)現(xiàn)這些方法的可選擇的途徑,這樣可以使執(zhí)行這些的類避免把這些成員設(shè)定為公共的。C#類實(shí)現(xiàn)接口成員可以用有效的名稱。
【編輯推薦】