これらの例では、 Func
および Action
ジェネリック デリゲートで共変性と反変性を使用して、メソッドの再利用を可能にし、コードの柔軟性を高める方法を示します。
共変性と反変性の詳細については、「 デリゲートの分散 (Visual Basic)」を参照してください。
共変型パラメーターでデリゲートを使用する
次の例は、ジェネリック Func
デリゲートでの共分散サポートの利点を示しています。
FindByTitle
メソッドは、String
型のパラメーターを受け取り、Employee
型のオブジェクトを返します。 ただし、Func(Of String, Person)
はEmployee
を継承するため、このメソッドを Person
デリゲートに割り当てることができます。
' Simple hierarchy of classes.
Public Class Person
End Class
Public Class Employee
Inherits Person
End Class
Class Finder
Public Shared Function FindByTitle(
ByVal title As String) As Employee
' This is a stub for a method that returns
' an employee that has the specified title.
Return New Employee
End Function
Sub Test()
' Create an instance of the delegate without using variance.
Dim findEmployee As Func(Of String, Employee) =
AddressOf FindByTitle
' The delegate expects a method to return Person,
' but you can assign it a method that returns Employee.
Dim findPerson As Func(Of String, Person) =
AddressOf FindByTitle
' You can also assign a delegate
' that returns a more derived type to a delegate
' that returns a less derived type.
findPerson = findEmployee
End Sub
End Class
反変型パラメーターでのデリゲートの使用
次の例は、ジェネリック Action
デリゲートでの反変性サポートの利点を示しています。
AddToContacts
メソッドは、Person
型のパラメーターを受け取ります。 ただし、Action(Of Employee)
はEmployee
を継承するため、このメソッドを Person
デリゲートに割り当てることができます。
Public Class Person
End Class
Public Class Employee
Inherits Person
End Class
Class AddressBook
Shared Sub AddToContacts(ByVal person As Person)
' This method adds a Person object
' to a contact list.
End Sub
Sub Test()
' Create an instance of the delegate without using variance.
Dim addPersonToContacts As Action(Of Person) =
AddressOf AddToContacts
' The Action delegate expects
' a method that has an Employee parameter,
' but you can assign it a method that has a Person parameter
' because Employee derives from Person.
Dim addEmployeeToContacts As Action(Of Employee) =
AddressOf AddToContacts
' You can also assign a delegate
' that accepts a less derived parameter
' to a delegate that accepts a more derived parameter.
addEmployeeToContacts = addPersonToContacts
End Sub
End Class
こちらも参照ください
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET