Aracılığıyla paylaş


Func ve Action Genel Yetkilileri için Varyansı Kullanma (Visual Basic)

Bu örnekler, yöntemlerin yeniden kullanılmasını sağlamak ve kodunuzda daha fazla esneklik sunmak amacıyla Func ve Action genel temsilcilerde kovaryans ve kontravaryansı nasıl kullanacağınızı gösterir.

Kovaryans ve kontrvaryans hakkında daha fazla bilgi için bkz. Temsilcilerde Varyans (Visual Basic).

Kovaryant Tür Parametreleriyle Temsilcileri Kullanma

Aşağıdaki örnek, genel Func temsilcilerde kovaryans desteğinin avantajlarını göstermektedir. FindByTitle yöntemi, String türünde bir parametre alır ve Employee türünde bir nesne döndürür. Ancak, Func(Of String, Person)Employee'den devraldığı için Person temsilciye bu yöntemi atayabilirsiniz.

' 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

Delegeleri Kontravaryant Tür Parametreleriyle Kullanma

Aşağıdaki örnek, genel Action temsilcilerde değişken karşıtı desteğin avantajlarını göstermektedir. AddToContacts yöntemi, Person türünde bir parametre alır. Ancak, Action(Of Employee)Employee'den devraldığı için Person temsilciye bu yöntemi atayabilirsiniz.

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

Ayrıca bakınız