接口

VB 6.0中提供了接口,在没有继承的情况下,它可以前期绑定的方式实现多态。在本套书的VB篇中大量使用了接口技术。在.NET中,任何对象都有一个本地接口,使用Implements关键字(VB.NET中)或冒号(VC#.NET中)可以实现辅助接口。

创建IGElement接口

.NET中接口的概念与VB6.0中的基本相同,但实现方式不太一样。例如前面的CGElement基类,把它重新定义为接口的形式,如下所示:

【VB.NET】

code.vb.net
Public Interface IGElement
    Property ID() As Integer
    Sub Draw()
End Interface

【VC#.NET】

code.vc#.net
public interface IGElement
{
    int ID
    {
        get;
        set:
    }
    void Draw();
}

其中必须使用Interface关键字或interface关键字。在VB.NET中定义属性只需要在Property 后面跟属性名称和类型,不需要属性过程;定义方法只需要在过程关键字后面给出方法名;属性和方法都不需要使用Private, Public等指定范围。在VC#.NET中定义属性时需要给出get和set,方法只需要给出方法名。

实现IGElement接口

在VB.NET中实现接口需要使用Implements关键字,VC#.NET 中则像指定继承关系那样使用冒号。

【VB.NET】

code.vb.net
Public Class CLine
    Implements IGElement
    Private m_ID As Integer
    Private m_Begin,m_End As PointF
    Public Property ID() As Integer Implements IGElement.ID
        Get
            Return m_ID
        End Get
        Set(ByVal Value As Integer)
            m_ID=Value
        End Set
    End Property
    Public Sub Draw() Implements IGElement.Draw
        text-blue-400">Console.text-blue-400">WriteLine("绘直线段。")
    End Sub
End Class

【VC#.NET】

code.vc#.net
public class CLine:IGElement
{
    public Cline()
    {
    }
    private int m_ ID;
    private PointF m_Begin,m_End;
    public int ID
    {
        get(return m_ID;)
        set m_ID=value;)
    }
    public void DrawO
    {
        Console.WriteLine("绘直线段。");
}
}

测试IGElement接口

定义接口并创建实现接口的类以后,在Form1类中添加下面的代码进行测试。首先创建一个IGElement类型的接口,用它引用CLine类实例,然后将它的ID属性设置为1,并调用Draw 方法。

【VB.NET】

code.vb.net
Private Sub Form1_Load(ByVal sender As System.Object,_
            ByVal text-blue-400">e As System.EventArgs) Handles MyBase.Load
    Dim ge As IGElement = New CLine()
    ge.ID=1
    text-blue-400">Console.text-blue-400">WriteLine("ID: {0}", ge.ID)
    ge.Draw()
End Sub

【VC#.NET】

code.vc#.net
private void Form1_Load(object sender, System.EventArgs e)
{
    IGElement ge= new CLine();
    ge.ID=1;
    Console.WriteLine("ID:{0}", ge.ID);
    ge.Draw();
}

输出窗口中的结果如图2-3所示。

Document Image
\[\]

图2-3 接口测试