对 Func 和 Action 泛型委托使用变体 (Visual Basic)

这些示例演示如何在泛型委托FuncAction中使用协变和逆变,以便重复利用方法,并在代码中提供更大的灵活性。

有关协变和逆变的详细信息,请参阅委托中的变体 (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

另请参阅