第一节 接口慨述
接口(interface)用来定义一种程序的协定。实现接口的类或者结构要与接口的定义
严格一致。有了这个协定,就可以抛开编程语言的限制(理论上)。接口可以从多个基接
口继承,而类或结构可以实现多个接口。接口可以包含方法、属性、事件和索引器。接口
本身不提供它所定义的成员的实现。接口只指定实现该接口的类或接口必须提供的成员。
接口好比一种模版,这种模版定义了对象必须实现的方法,其目的就是让这些方法可
以作为接口实例被引用。接口不能被实例化。类可以实现多个接口并且通过这些实现的接
口被索引。接口变量只能索引实现该接口的类的实例。例子:
interface IMyExample {
string this[int index] { get ; set ; }
event EventHandler Even ;
void Find(int value) ;
string Point { get ; set ; }
}
public delegate void EventHandler(object sender, Event e) ;
上面例子中的接口包含一个索引 this、一个事件 Even、一个方法 Find 和一个属性
Point。
接口可以支持多重继承。就像在下例中,接口"IComboBox"同时
从"ITextBox"和"IListBox"继承。
interface IControl {
void Paint( ) ;
}
interface ITextBox: IControl {
void SetText(string text) ;
}
interface IListBox: IControl {
void SetItems(string[] items) ;
}
interface IComboBox: ITextBox, IListBox { }
类和结构可以多重实例化接口。就像在下例中,类"EditBox"继承了类"Control",同时
从"IDataBound"和"IControl"继承。
interface IDataBound {
void Bind(Binder b) ;
}
public class EditBox: Control, IControl, IDataBound {
public void Paint( ) ;
评论0