接口Interfaces
接口可以采用多重继承。在以下示例中,接口 同时继承自 ITextBox
和 IListBox
。
interface IDataBound
{
void Bind(Binder b);
}
{
public void Bind(Binder b) { }
}
当类或结构实现特定接口时,此类或结构的实例可以隐式转换成相应的接口类型。例如
object obj = new EditBox();
IDataBound dataBound = (IDataBound)obj;
在前面的 EditBox
类中,IControl
接口中的 Paint
方法和 接口中的 Bind
方法均使用公共成员进行实现。C# 还支持显式接口成员实现代码,这样类或结构就不会将成员设为公共成员。显式接口成员实现代码是使用完全限定的接口成员名称进行编写。例如,EditBox
类可以使用显式接口成员实现代码来实现 IControl.Paint
和 IDataBound.Bind
方法,如下所示。
EditBox editBox = new EditBox();
editBox.Paint(); // Error, no such method
IControl control = editBox;
control.Paint(); // Ok