基于接口的多态性

更新:2007 年 11 月

接口提供了在 Visual Basic 中实现多态性的另一种方法。接口描述属性和方法的方式与类相似,但与类不同,接口不能提供任何实现。多个接口具有允许软件组件的系统不断发展而不破坏现有代码的优点。

若要使用接口实现多态性,应在几个类中以不同的方式实现接口。客户端应用程序可以以完全相同的方式使用旧实现或新实现。基于接口的多态性的优点是,不需要重新编译现有的客户端应用程序就可以使用新的接口实现。

下面的示例定义名为 Shape2 的接口,该接口在名为 RightTriangleClass2 和 RectangleClass2 的类中实现。名为 ProcessShape2 的过程调用 RightTriangleClass2 或 RectangleClass2 实例的 CalculateArea 方法:

Sub TestInterface()
    Dim RectangleObject2 As New RectangleClass2
    Dim RightTriangleObject2 As New RightTriangleClass2
    ProcessShape2(RightTriangleObject2, 3, 14)
    ProcessShape2(RectangleObject2, 3, 5)
End Sub

Sub ProcessShape2(ByVal Shape2 As Shape2, ByVal X As Double, _
      ByVal Y As Double)
    MsgBox("The area of the object is " _
       & Shape2.CalculateArea(X, Y))
End Sub

Public Interface Shape2
    Function CalculateArea(ByVal X As Double, ByVal Y As Double) As Double
End Interface

Public Class RightTriangleClass2
    Implements Shape2
    Function CalculateArea(ByVal X As Double, _
          ByVal Y As Double) As Double Implements Shape2.CalculateArea
        ' Calculate the area of a right triangle. 
        Return 0.5 * (X * Y)
    End Function
End Class

Public Class RectangleClass2
    Implements Shape2
    Function CalculateArea(ByVal X As Double, _
          ByVal Y As Double) As Double Implements Shape2.CalculateArea
        ' Calculate the area of a rectangle. 
        Return X * Y
    End Function
End Class

请参见

任务

如何:创建和实现接口

概念

基于继承的多态性