C#實現(xiàn)多個接口淺析
本文向大家介紹C#實現(xiàn)多個接口,可能好多人還不知道C#實現(xiàn)多個接口,沒有關(guān)系,看完本文你肯定有不少收獲,希望本文能教會你更多東西。
一個接口定義一個協(xié)定。C#實現(xiàn)多個接口的類或結(jié)構(gòu)必須遵守其協(xié)定。接口可以包含方法、屬性、索引器和事件作為成員。
- interface IExample
- {
- string this[int index] { get; set; }
- event EventHandler E;
- void F(int value);
- string P { get; set; }
- }
- public delegate void EventHandler(object sender, EventArgs e);
顯示了一個包含索引器、事件 E、方法 F 和屬性 P 的接口。接口可以使用多重繼承。在下面的示例中,
- 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 繼承。類和結(jié)構(gòu)可以實現(xiàn)多個接口。在下面的示例中,
- interface IDataBound
- {
- void Bind(Binder b);
- }
- public class EditBox: Control, IControl, IDataBound
- {
- public void Paint() {...}
- public void Bind(Binder b) {...}
- }
類 EditBox 從類 Control 派生,并且同時實現(xiàn) IControl 和 IDataBound。
在前面的示例中,IControl 接口中的 Paint 方法和 IDataBound 接口中的 Bind 方法是使用 EditBox 類的公共成員實現(xiàn)的。C# 提供了另一種方式來實現(xiàn)這些方法,使得實現(xiàn)類避免將這些成員設(shè)置成公共的。這就是:接口成員可以用限定名來實現(xiàn)。例如,在 EditBox 類中將 Paint 方法命名為 IControl.Paint,將 Bind 方法命名為 IDataBound.Bind 方法。
- public class EditBox: IControl, IDataBound
- {
- void IControl.Paint() {...}
- void IDataBound.Bind(Binder b) {...}
- }
用這種方式C#實現(xiàn)多個接口成員稱為顯式接口成員,這是因為每個成員都顯式地指定要實現(xiàn)的接口成員。顯式接口成員只能通過接口來調(diào)用。例如,在 EditBox 中實現(xiàn)的 Paint 方法只能通過強制轉(zhuǎn)換為 IControl 接口來調(diào)用。
- 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
- }
- }
【編輯推薦】