共用方式為


在委派中使用變數 (Visual Basic)

當您將方法指派給委派時, 共變數反變數 可提供彈性來比對具有方法簽章的委派類型。 共變數允許方法的傳回型別比委派中所定義的衍生類型還要多。 Contravariance 允許方法具有比委派類型中更低衍生的參數類型。

範例 1:共變數

說明

這個範例示範如何搭配方法使用委派,這些方法具有衍生自委派簽章中傳回型別的方法。 DogsHandler 返回的資料類型是 Dogs 類型,該類型從委派中定義的 Mammals 類型衍生而來。

程式碼

Class Mammals
End Class

Class Dogs
    Inherits Mammals
End Class
Class Test
    Public Delegate Function HandlerMethod() As Mammals
    Public Shared Function MammalsHandler() As Mammals
        Return Nothing
    End Function
    Public Shared Function DogsHandler() As Dogs
        Return Nothing
    End Function
    Sub Test()
        Dim handlerMammals As HandlerMethod = AddressOf MammalsHandler
        ' Covariance enables this assignment.
        Dim handlerDogs As HandlerMethod = AddressOf DogsHandler
    End Sub
End Class

範例 2:反變數

說明

此範例示範如何使用委派來搭配那些其參數類型為委派簽名參數基礎類型的方法。 使用反變數時,您可以使用一個事件處理程式,而不是個別的處理程式。 下列範例會使用兩個委派:

  • KeyEventHandler委派,定義 Button.KeyDown 事件的簽章。 其簽章為:

    Public Delegate Sub KeyEventHandler(sender As Object, e As KeyEventArgs)
    
  • 定義MouseEventHandler事件簽章的委派。 其簽章為:

    Public Delegate Sub MouseEventHandler(sender As Object, e As MouseEventArgs)
    

此範例會使用 EventArgs 參數定義事件處理程式,並用它來處理 Button.KeyDownButton.MouseClick 事件。 它能夠這樣做是因為 EventArgsKeyEventArgsMouseEventArgs 的基底類型。

程式碼

' Event handler that accepts a parameter of the EventArgs type.
Private Sub MultiHandler(ByVal sender As Object,
                         ByVal e As System.EventArgs)
    Label1.Text = DateTime.Now
End Sub

Private Sub Form1_Load(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles MyBase.Load

    ' You can use a method that has an EventArgs parameter,
    ' although the event expects the KeyEventArgs parameter.
    AddHandler Button1.KeyDown, AddressOf MultiHandler

    ' You can use the same method
    ' for the event that expects the MouseEventArgs parameter.
    AddHandler Button1.MouseClick, AddressOf MultiHandler
End Sub

另請參閱