0

请看下面的代码:

    Public Class Student
    Public Sub PassList(ByVal StudentList As List(Of Student))
        Dim s1 As New Student
        Dim s2 As New Student
        Dim s3 As New Student
        StudentList.Add(s1)
        StudentList.Add(s2)
        StudentList.Add(s3)
    End Sub

    Public Sub TestReturnList()
        Dim list As List(Of PostGraduate)
        PassList(list)
    End Sub

End Class

Public Class PostGraduate
    Inherits Student
End Class

Public Class PostUndergraduate
    Inherits Student
End Class

有一个编译器错误:

'System.Collections.Generic.List(Of WindowsApplication1.PostGraduate)' 类型的值无法转换为 'System.Collections.Generic.List(Of WindowsApplication1.Student)

我理解错误的原因。有解决方法吗?

4

1 回答 1

1

你的问题是关于方差的。尝试改变这个:

Public Sub PassList(ByVal StudentList As List(Of Student))

End Sub

对此:

Public Sub PassList(ByVal StudentList As IEnumerable(Of Student))

End Sub

泛型类型参数的变体是 .NET 4.0 中的一项新功能。

在此处阅读有关协变和逆变的更多信息。

于 2013-04-02T13:46:55.103 回答