通用多态性

时间:2013-04-02 13:38:13

标签: vb.net

请查看以下代码:

    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)

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

1 个答案:

答案 0 :(得分: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中的一项新功能。

详细了解Covariance and Contravariance here