将通用列表作为类型参数传递

时间:2013-12-12 00:29:49

标签: .net vb.net generics inheritance covariance

有没有办法调用来调用MainApplication.CallDoSomething中的Me.DoSomething2来处理下面的代码。

Public Interface ICovariance(Of Out T As Grandparent) 
End Interface
Public MustInherit Class Grandparent
End Class
Public Class Parent : Inherits Grandparent
End Class
Public Class Child : Inherits Parent
End Class
Public Class CustomList(Of T As Grandparent) : Implements ICovariance(Of T)
End Class
Public Class CustomList2(Of T As Parent)
    Inherits CustomList(Of T)

    Public Sub MyCustomList2Method()
    End Sub
End Class
Public Class MainApplication
    Public Sub CallDoSomething()
        'This Works
        Me.DoSomething(Of CustomList2(Of Child))()

        'This does not work
         Me.DoSomething2(Of CustomList2(Of Child))()
    End Sub

    ' This method works because of the interface and covariance 
    Public Function DoSomething(Of T As {ICovariance(Of Grandparent), New})() As T
        Dim instance As New T

        'This method can't be called because I'm working with an interface
        instance.MyCustomList2Method()
        Return instance
    End Function

    ' This method does not work. 
    ' I want T to be a CustomList2 that contains Parent 
    ' (or anything that inherits Parent)
    Public Function DoSomething2(Of T As {CustomList2(Of Parent), New})() As T
        Dim instance As New T

        'This method would work if I could call this method
        instance.MyCustomList2Method()

        Return instance
    End Function
End Class

据我所知,DoSomething2上的类型参数需要一个CustomList2(Of Parent),但我想将Customlist2(Of Child)传递给它。我可以使用协方差的接口来实现这一点。使用接口不允许我调用方法,例如CustomList2.MyCustomerList2Method。

这是一个简化的例子,任何人都可以提供一些见解吗?

1 个答案:

答案 0 :(得分:1)

尝试将第二个泛型类型参数添加到第二个方法:

Public Function DoSomething2(Of T1 As {Parent}, T2 As {CustomList2(Of T1), New})() As T2
    Dim instance As New T2

    'This method would work if I could call this method
    instance.MyCustomList2Method()

    Return instance
End Function

当它看起来像这样时,你可以这样称呼它:

Me.DoSomething2(Of Child, CustomList2(Of Child))()