登录
  • 欢迎访问 Sharezer Blog

【C#笔记】接口 (interface)

C# sharezer 1904次浏览 已收录 0个评论

接口 (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


Sharezer , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明【C#笔记】接口 (interface)
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址