在泛型集合的接口中使用变体 (Visual Basic)

协变接口允许其方法返回的派生类型比接口中指定的类型多。 逆变接口允许其方法接受的派生类型的参数比接口中指定的参数少。

在 .NET Framework 4 中,多个现有接口变为协变和逆变。 包括 IEnumerable<T>IComparable<T>。 这使您能够将操作基类型泛型集合的方法重复用于派生类型集合。

有关 .NET Framework 中变体接口的列表,请参阅泛型接口中的变体(Visual Basic)。

转换泛型集合

下面的示例演示了接口中 IEnumerable<T> 协变支持的好处。 该方法 PrintFullName 接受类型集合 IEnumerable(Of Person) 作为参数。 但是,你可以将其重新用于IEnumerable(Of Person)类型的集合,因为Employee继承Person

' Simple hierarchy of classes.
Public Class Person
    Public Property FirstName As String
    Public Property LastName As String
End Class

Public Class Employee
    Inherits Person
End Class

' The method has a parameter of the IEnumerable(Of Person) type.
Public Sub PrintFullName(ByVal persons As IEnumerable(Of Person))
    For Each person As Person In persons
        Console.WriteLine(
            "Name: " & person.FirstName & " " & person.LastName)
    Next
End Sub

Sub Main()
    Dim employees As IEnumerable(Of Employee) = New List(Of Employee)

    ' You can pass IEnumerable(Of Employee),
    ' although the method expects IEnumerable(Of Person).

    PrintFullName(employees)

End Sub

比较泛型集合

以下示例演示了接口中 IComparer<T> 逆变支持的优点。 PersonComparer 类实现 IComparer(Of Person) 接口。 但是,可以重复使用这个类来比较一系列Employee类型的对象,因为Employee继承自Person

' Simple hierarchy of classes.
Public Class Person
    Public Property FirstName As String
    Public Property LastName As String
End Class

Public Class Employee
    Inherits Person
End Class
' The custom comparer for the Person type
' with standard implementations of Equals()
' and GetHashCode() methods.
Class PersonComparer
    Implements IEqualityComparer(Of Person)

    Public Function Equals1(
        ByVal x As Person,
        ByVal y As Person) As Boolean _
        Implements IEqualityComparer(Of Person).Equals

        If x Is y Then Return True
        If x Is Nothing OrElse y Is Nothing Then Return False
        Return (x.FirstName = y.FirstName) AndAlso
            (x.LastName = y.LastName)
    End Function
    Public Function GetHashCode1(
        ByVal person As Person) As Integer _
        Implements IEqualityComparer(Of Person).GetHashCode

        If person Is Nothing Then Return 0
        Dim hashFirstName =
            If(person.FirstName Is Nothing,
            0, person.FirstName.GetHashCode())
        Dim hashLastName = person.LastName.GetHashCode()
        Return hashFirstName Xor hashLastName
    End Function
End Class

Sub Main()
    Dim employees = New List(Of Employee) From {
        New Employee With {.FirstName = "Michael", .LastName = "Alexander"},
        New Employee With {.FirstName = "Jeff", .LastName = "Price"}
    }

    ' You can pass PersonComparer,
    ' which implements IEqualityComparer(Of Person),
    ' although the method expects IEqualityComparer(Of Employee)

    Dim noduplicates As IEnumerable(Of Employee) = employees.Distinct(New PersonComparer())

    For Each employee In noduplicates
        Console.WriteLine(employee.FirstName & " " & employee.LastName)
    Next
End Sub

另请参阅