自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C#實現(xiàn)多個接口淺析

開發(fā) 后端
這里介紹C#實現(xiàn)多個接口成員稱為顯式接口成員,這是因為每個成員都顯式地指定要實現(xiàn)的接口成員。顯式接口成員只能通過接口來調(diào)用。

本文向大家介紹C#實現(xiàn)多個接口,可能好多人還不知道C#實現(xiàn)多個接口,沒有關(guān)系,看完本文你肯定有不少收獲,希望本文能教會你更多東西。

一個接口定義一個協(xié)定。C#實現(xiàn)多個接口的類或結(jié)構(gòu)必須遵守其協(xié)定。接口可以包含方法、屬性、索引器和事件作為成員。

  1. interface IExample  
  2. {  
  3.    string this[int index] { get; set; }  
  4.    event EventHandler E;  
  5.    void F(int value);  
  6.    string P { get; set; }  
  7. }  
  8. public delegate void EventHandler(object sender, EventArgs e); 

顯示了一個包含索引器、事件 E、方法 F 和屬性 P 的接口。接口可以使用多重繼承。在下面的示例中,

  1. interface IControl  
  2. {  
  3.    void Paint();  
  4. }  
  5. interface ITextBox: IControl  
  6. {  
  7.    void SetText(string text);  
  8. }  
  9. interface IListBox: IControl  
  10. {  
  11.    void SetItems(string[] items);  
  12. }  
  13. interface IComboBox: ITextBox, IListBox {} 

接口 IComboBox 同時從 ITextBox 和 IListBox 繼承。類和結(jié)構(gòu)可以實現(xiàn)多個接口。在下面的示例中,

  1. interface IDataBound  
  2. {  
  3.    void Bind(Binder b);  
  4. }  
  5. public class EditBox: Control, IControl, IDataBound  
  6. {  
  7.    public void Paint() {...}  
  8.    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 方法。

  1. public class EditBox: IControl, IDataBound  
  2. {  
  3.    void IControl.Paint() {...}  
  4.    void IDataBound.Bind(Binder b) {...}  

用這種方式C#實現(xiàn)多個接口成員稱為顯式接口成員,這是因為每個成員都顯式地指定要實現(xiàn)的接口成員。顯式接口成員只能通過接口來調(diào)用。例如,在 EditBox 中實現(xiàn)的 Paint 方法只能通過強制轉(zhuǎn)換為 IControl 接口來調(diào)用。

  1. class Test  
  2. {  
  3.    static void Main() {  
  4.       EditBox editbox = new EditBox();  
  5.       editbox.Paint();   // error: no such method  
  6.       IControl control = editbox;  
  7.       control.Paint();   // calls EditBox's Paint implementation  
  8.    }  

【編輯推薦】

  1. C# 3.0編譯器簡單介紹
  2. C#使用函數(shù)重載學(xué)習(xí)筆記
  3. Visual C#對數(shù)據(jù)庫處理概述
  4. C#具有隱式類型聲明描述
  5. C#使用SharpZipLib分析
責(zé)任編輯:佚名 來源: 博客園
相關(guān)推薦

2009-08-31 16:48:02

C#實現(xiàn)IDispos

2009-09-04 13:22:31

C#實現(xiàn)多個接口

2009-08-27 18:09:49

C#接口的實現(xiàn)

2009-08-27 14:29:28

顯式實現(xiàn)接口

2009-09-02 13:36:58

C#實現(xiàn)多個接口

2009-08-07 08:53:52

C# ICloneab

2009-08-27 17:59:56

C#接口定義

2009-08-31 17:02:28

C#接口編程

2009-09-28 14:45:22

C#接口的定義

2009-08-24 15:12:13

C# 泛型接口

2009-09-27 10:43:13

C#合并多個WORD文

2009-09-02 15:34:37

C#實現(xiàn)插件構(gòu)架

2009-08-27 13:05:06

C#接口特點C#接口實例

2009-08-31 16:37:20

C#接口定義

2009-09-18 19:21:17

C#接口

2010-01-14 17:13:53

C++接口

2009-08-31 15:55:17

C#實現(xiàn)Strateg

2009-08-28 15:57:56

C#線程傳遞參數(shù)

2009-08-21 09:20:44

C#異步套接字

2009-09-09 11:29:32

C# TextBox事
點贊
收藏

51CTO技術(shù)棧公眾號