HOW TO:建立部分方法 (Visual Basic)

部分方法能讓開發人員將自訂邏輯插入至設計工具產生的程式碼,這麼做的目的通常是為了進行資料驗證。 建立部分方法共有兩個部分:定義方法簽章,以及撰寫實作 (Implementation)。 通常,定義是由程式碼產生器的設計工具撰寫,而實作是由使用所產生之程式碼的開發人員撰寫。 如需詳細資訊,請參閱部分方法 (Visual Basic)

若要定義方法簽章

  1. 在部分類別中,以關鍵字 Partial 開始簽章。

  2. 使用 Private 做為存取修飾詞 (Modifier)。

  3. 加入關鍵字 Sub。 方法必須是 Sub 程序。

  4. 撰寫方法的名稱。

  5. 提供方法的參數清單。

  6. 以 End Sub 結束方法。

若要實作方法

  1. 使用 Private 做為存取修飾詞。

  2. 加入任何想要的其他修飾詞。

  3. 撰寫方法的名稱,該名稱必須符合簽章定義中的名稱。

  4. 加入參數清單。 參數名稱必須符合簽章中的名稱。 參數資料型別可以省略。

  5. 定義方法的主體。

  6. 以 End Sub 陳述式 (Statement) 關閉。

範例

部分方法的定義和實作通常位於不同的檔案中,這些檔案都是使用部分類別建立的。 通常,部分方法的目的是用來提供專案中的變更通知。

在下列範例中,會開發並呼叫名為 OnNameChanged 的部分方法。 方法簽章是在檔案 Customer.Designer.vb 的部分類別 Customer 中定義。 實作則位在檔案 Customer.vb 的部分類別 Customer 中,另外會在使用類別的專案中建立 Customer 的執行個體 (Instance)。

結果是包含下列訊息的訊息方塊:

Name was changed to: Blue Yonder Airlines.

' File Customer.Designer.vb provides a partial class definition for
' Customer, which includes the signature for partial method 
' OnNameChanged.
Partial Class Customer
    Private _Name As String
    Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
            OnNameChanged()
        End Set
    End Property

    ' Definition of the partial method signature.
    Partial Private Sub OnNameChanged()

    End Sub
End Class
' In a separate file, a developer who wants to use the partial class
' and partial method fills in an implementation for OnNameChanged.
Partial Class Customer

    ' Implementation of the partial method.
    Private Sub OnNameChanged()
        MsgBox("Name was changed to " & Me.Name)
    End Sub
End Class
Module Module1

    Sub Main()
        ' Creation of cust will invoke the partial method.
        Dim cust As New Customer With {.Name = "Blue Yonder Airlines"}
    End Sub
End Module

請參閱

參考

Partial (Visual Basic)

概念

部分方法 (Visual Basic)