当前位置:首页 > 网络编程 > 软件语言 > .NET > C# 语言规范--1.9 接口

C# 语言规范--1.9 接口

点击次数:45 次 发布日期:2008-11-06 08:04:28 作者:源代码网
源代码网推荐
广告载入中

一个接口定义一个协定。实现接口的类或结构必须遵守其协定。接口可以包含方法、属性、索引器和事件作为成员。

示例

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 同时从 ITextBoxIListBox 继承。

软件开发网 www.mscto.com

类和结构可以实现多个接口。在下面的示例中,

interface IDataBound

{

   void Bind(Binder b);

}

public class EditBox: Control, IControl, IDataBound

{

   public void Paint() {...}

   public void Bind(Binder b) {...}

}   

EditBox 从类 Control 派生,并且同时实现 IControlIDataBound

在前面的示例中,IControl 接口中的 Paint 方法和 IDataBound 接口中的 Bind 方法是使用 EditBox 类的公共成员实现的。C# 提供了另一种方式来实现这些方法,使得实现类避免将这些成员设置成公共的。这就是:接口成员可以用限定名来实现。例如,在 EditBox 类中将 Paint 方法命名为 IControl.Paint,将 Bind 方法命名为 IDataBound.Bind 方法。

public class EditBox: IControl, IDataBound

{

   void IControl.Paint() {...}

   void IDataBound.Bind(Binder b) {...}

}  

用这种方式实现的接口成员称为显式接口成员,这是因为每个成员都显式地指定要实现的接口成员。显式接口成员只能通过接口来调用。例如,在 EditBox 中实现的 Paint 方法只能通过强制转换为 IControl 接口来调用。

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

   }

}  


源代码网推荐

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华