這些範例示範如何在 和 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