Implements 陳述式

指定一或多個介面或介面成員,而其必須在其出現的類別或結構定義中進行實作。

語法

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

組件

interfacename
必要。 要由類別或結構中對應成員實作其屬性、程序和事件的介面。

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

備註

介面是代表介面所封裝成員的原型集合 (屬性、程序和事件)。 介面只會包含成員的宣告;類別和結構會實作這些成員。 如需詳細資訊,請參閱介面

Implements 陳述式必須緊接在 ClassStructure 陳述式後面。

當您實作介面時,必須實作介面中所宣告的所有成員。 省略任何成員會視為語法錯誤。 若要實作個別成員,當您在類別或結構中宣告成員時,可以指定 Implements 關鍵字 (這與 Implements 陳述式不同)。 如需詳細資訊,請參閱介面

類別可以使用屬性和程序的 Private 實作,但這些成員只能將實作類別的執行個體強制型轉成宣告為介面類別的變數,才能存取這些成員。

範例 1

下列範例顯示如何使用 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 關鍵字作為其成員宣告的一部分,以指出其實作該介面成員。

範例 2

下列兩個程序顯示如何使用上述範例中所實作的介面。 若要測試實作,請將這些程序新增至專案,並呼叫 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

另請參閱