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);
显示了一个包含索引器、事件 接口可以使用多重继承。在下面的示例中, interface IControl
{
void Paint();
}
interface ITextBox: IControl
{
void SetText(string text);
}
interface IListBox: IControl
{
void SetItems(string[] items);
}
interface IComboBox: ITextBox, IListBox {}
接口 软件开发网 www.mscto.com
类和结构可以实现多个接口。在下面的示例中, interface IDataBound
{
void Bind(Binder b);
}
public class EditBox: Control, IControl, IDataBound
{
public void Paint() {...}
public void Bind(Binder b) {...}
}
类 在前面的示例中, 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
}
}
源代码网推荐 源代码网供稿. |
