【C#语言规范版本5.0学习】1.8 接口

接口 (interface) 定义了一个可由类和结构实现的协定。

接口可以包含方法、属性、事件和索引器。

接口不提供它所定义的成员的实现(它仅指定实现该接口的类或结构必须提供的成员)。 接口可支持多重继承。在下面的示例中,接口 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 实现了 IControl 和 IDataBound。

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

当类或结构实现某个特定接口时,该类或结构的实例可以隐式地转换为该接口类型例如

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

在无法静态知道某个实例是否实现某个特定接口的情况下,可以使用动态类型强制转换。例如,下面的语句使用动态类型强制转换获取对象的 IControl 和 IDataBound 接口实现由于该对象的实际类型为 EditBox,此强制转换成功。

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

在前面的 EditBox 类中,来自 IControl 接口的 Paint 方法和来自 IDataBound 接口的 Bind 方法是使用 public 成员实现的。C# 还支持显式接口成员实现类或结构可以使用它来避免将成员声明为 public。显式接口成员实现使用完全限定的接口成员名。例如,EditBox 类可以使用显式接口成员实现来实现 IControl.Paint 和 IDataBound.Bind 方法,如下所示。

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

显式接口成员只能通过接口类型来访问。例如,要调用上面 EditBox 类提供的 IControl.Paint 实现, 必须首先将 EditBox 引用转换为 IControl 接口类型。

EditBox editBox = new EditBox();
editBox.Paint(); // Error, no such method
IControl control = editBox;
control.Paint(); // Ok
原文地址:https://www.cnblogs.com/TechSingularity/p/14334923.html