共用方式為


實現語句

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

語法

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

組件

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

interfacemember
必須的。 正在實作之介面的成員。

備註

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

語句Implements必須緊接在 或 Structure 語句後面Class

當您實作介面時,您必須實作介面中宣告的所有成員。 省略任何成員會被視為語法錯誤。 若要實作個別成員,您可以在類別或結構中宣告成員時,指定 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

另請參閱