Implements 陳述式

指定必須在所在類別或結構定義中實作的一或多個介面或是介面成員。

Implements interfacename [, ...]
-or-
Implements interfacename.interfacemember [, ...]

組件

  • interfacename
    必要項。 屬性 (Property)、程序及事件將透過類別或結構中對應成員實作的介面。

  • interfacemember
    必要項。 要實作介面的成員。

備註

介面是原型 (Prototype) 的集合,代表介面封裝的成員 (屬性、成員及事件)。 介面只包含成員的宣告;類別和結構則實作這些成員。

Implements 陳述式必須緊跟在 Class 或 Structure 陳述式之後。

當您實作介面時,您必須實作所有在介面中宣告的成員。 省略任一成員將被視為是語法錯誤。 若要實作個別成員,您可以在類別或結構中宣告時成員時,指定 Implements 子句 (Visual Basic) 關鍵字 (此關鍵字必須在 Implements 陳述式外另行指定)。 如需詳細資訊,請參閱介面 (Visual Basic)

類別可以使用屬性和程序的 Private (Visual Basic) 實作,但是這些成員的存取只能透過將實作類別之執行個體 (Instance) 轉換成已宣告為介面型別的變數來進行。

範例

下列範例會顯示如何使用 Implements 陳述式實作介面的成員。 它會定義名為 ICustomerInfo 的介面,此介面具有一個事件、一個屬性和一個程序。 customerInfo 類別則會實作在介面中定義的所有成員。

Public Interface ICustomerInfo
    Event updateComplete()
    Property customerName() As String
    Sub updateCustomerStatus()
End Interface

Public Class customerInfo
    Implements ICustomerInfo
    ' Storage for the property value.
    Private customerNameValue As String
    Public Event updateComplete() Implements ICustomerInfo.updateComplete
    Public Property CustomerName() As String _
        Implements ICustomerInfo.customerName
        Get
            Return customerNameValue
        End Get
        Set(ByVal value As String)
            ' The value parameter is passed to the Set procedure
            ' when the contents of this property are modified.
            customerNameValue = value
        End Set
    End Property

    Public Sub updateCustomerStatus() _
        Implements ICustomerInfo.updateCustomerStatus
        ' Add code here to update the status of this account.
        ' Raise an event to indicate that this procedure is done.
        RaiseEvent updateComplete()
    End Sub
End Class

請注意,customerInfo 類別會在另一行原始程式碼中使用 Implements 陳述式,指出類別會實作 ICustomerInfo 介面的所有成員。 接著,類別中的每個成員都會使用 Implements 關鍵字,做為成員宣告的一部分,指出它會實作該介面成員。

以下兩個程序將顯示如何使用上述範例中所實作的介面。 若要測試實作,請將這些程序加入至您的專案中,並呼叫 testImplements 程序。

Public Sub testImplements()
    ' This procedure tests the interface implementation by
    ' creating an instance of the class that implements ICustomerInfo.
    Dim cust As ICustomerInfo = New customerInfo()
    ' Associate an event handler with the event that is raised by
    ' the cust object.
    AddHandler cust.updateComplete, AddressOf handleUpdateComplete
    ' Set the customerName Property
    cust.customerName = "Fred"
    ' Retrieve and display the customerName property.
    MsgBox("Customer name is: " & cust.customerName)
    ' Call the updateCustomerStatus procedure, which raises the
    ' updateComplete event.
    cust.updateCustomerStatus()
End Sub

Sub handleUpdateComplete()
    ' This is the event handler for the updateComplete event.
    MsgBox("Update is complete.")
End Sub

請參閱

參考

Implements 子句 (Visual Basic)

Interface 陳述式 (Visual Basic)

其他資源

介面 (Visual Basic)