Visual Basic 中的接口实现示例

更新:2007 年 11 月

实现接口的类必须实现其所有的属性、方法和事件。

下面的示例定义了两个接口。第二个接口 Interface2 继承 Interface1 并定义附加属性和方法。

Interface Interface1
    Sub sub1(ByVal i As Integer)
End Interface

' Demonstrates interface inheritance.
Interface Interface2
    Inherits Interface1
    Sub M1(ByVal y As Integer)
    ReadOnly Property Num() As Integer
End Interface

下一个示例则实现上一示例中所定义的接口 Interface1:

Public Class ImplementationClass1
    Implements Interface1
    Sub Sub1(ByVal i As Integer) Implements Interface1.sub1
        ' Insert code here to implement this method.
    End Sub
End Class

最后一个示例则实现 Interface2,包括自 Interface1 继承的方法:

Public Class ImplementationClass2
    Implements Interface2
    Dim INum As Integer = 0
    Sub sub1(ByVal i As Integer) Implements Interface2.sub1
        ' Insert code here that implements this method.
    End Sub
    Sub M1(ByVal x As Integer) Implements Interface2.M1
        ' Insert code here to implement this method.
    End Sub

    ReadOnly Property Num() As Integer Implements _
       Interface2.Num
        Get
            Num = INum
        End Get
    End Property
End Class

请参见

任务

如何:创建和实现接口

演练:创建和实现接口

概念

接口概述

接口定义

Implements 关键字和 Implements 语句

何时使用接口

参考

Interface 语句 (Visual Basic)

Implements 语句