接口Interfaces

    接口可以采用多重继承在以下示例中,接口 同时继承自 ITextBoxIListBox

    1. interface IDataBound
    2. {
    3. void Bind(Binder b);
    4. }
    5. {
    6. public void Bind(Binder b) { }
    7. }

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

    1. object obj = new EditBox();
    2. IDataBound dataBound = (IDataBound)obj;

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

    1. EditBox editBox = new EditBox();
    2. editBox.Paint(); // Error, no such method
    3. IControl control = editBox;
    4. control.Paint(); // Ok