デリゲートの変性の使用 (Visual Basic)

メソッドをデリゲートに割り当てると、"共変性" と "反変性" により、デリゲート型をメソッドのシグネチャに柔軟に一致させることができます。 共変性により、メソッドの戻り値の型の派生を、デリゲートに定義されている型よりも強くできます。 また、反変性により、メソッドのパラメーター型の派生をデリゲート型よりも弱くできます。

例 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:反変性

説明

この例は、型がデリゲート シグネチャ パラメーター型の基本データ型であるパラメーターを持つメソッドでデリゲートを使用する方法を示しています。 反変性により、複数のハンドラーの代わりに単一のイベント ハンドラーを使用できます。 次の例では、2 つのデリゲートを使用します。

  • Button.KeyDown イベントのシグネチャを定義する KeyEventHandler デリゲート。 そのシグネチャ:

    Public Delegate Sub KeyEventHandler(sender As Object, e As KeyEventArgs)
    
  • Button.MouseClick イベントのシグネチャを定義する 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

関連項目