C#指南,重温基础,展望远方!(9)C#接口

接口定义了可由类和结构实现的协定。 接口可以包含方法属性事件索引器。 接口不提供所定义的成员的实现代码,仅指定必须由实现接口的类或结构提供的成员。

接口可以采用多重继承。 在以下示例中,接口 IComboBox 同时继承自 ITextBox 和 IListBox

C#
interface IControl
{
    void Paint();
}
interface ITextBox: IControl
{
    void SetText(string text);
}
interface IListBox: IControl
{
    void SetItems(string[] items);
}
interface IComboBox: ITextBox, IListBox {}

类和结构可以实现多个接口。 在以下示例中,类 EditBox 同时实现 IControl 和 IDataBound

C#
interface IDataBound
{
    void Bind(Binder b);
}
public class EditBox: IControl, IDataBound
{
    public void Paint() { }
    public void Bind(Binder b) { }
} 

当类或结构实现特定接口时,此类或结构的实例可以隐式转换成相应的接口类型。 例如

C#
EditBox editBox = new EditBox();
IControl control = editBox;
IDataBound dataBound = editBox;

如果已知实例不是静态地实现特定接口,可以使用动态类型显式转换功能。 例如,以下语句使用动态类型显式转换功能来获取对象的 IControl 和 IDataBound 接口实现代码。 因为对象的运行时实际类型是 EditBox,所以显式转换会成功。

C#
object obj = new EditBox();
IControl control = (IControl)obj;
IDataBound dataBound = (IDataBound)obj;

在前面的 EditBox 类中,IControl 接口中的 Paint 方法和 IDataBound 接口中的 Bind 方法均使用公共成员进行实现。C# 还支持显式接口成员实现代码,这样类或结构就不会将成员设为公共成员。 显式接口成员实现代码是使用完全限定的接口成员名称进行编写。 例如,EditBox 类可以使用显式接口成员实现代码来实现 IControl.Paint 和 IDataBound.Bind 方法,如下所示。

C#
public class EditBox: IControl, IDataBound
{
    void IControl.Paint() { }
    void IDataBound.Bind(Binder b) { }
}

显式接口成员只能通过接口类型进行访问。 例如,只有先将 EditBox 引用转换成 IControl 接口类型,才能调用上面 EditBox 类提供的 IControl.Paint 实现代码。

C#
EditBox editBox = new EditBox();
editBox.Paint();            // Error, no such method
IControl control = editBox;
control.Paint();            // Ok

posted on 2018-05-30 10:31  对你说早安  阅读(113)  评论(0编辑  收藏  举报

导航