简体   繁体   English

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

[英]Passing Generic List as Type Parameter

Is there any way to call to get the call to Me.DoSomething2 inside of MainApplication.CallDoSomething to work in the code below. 有什么方法可以调用来获取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

I understand that that type parameters on DoSomething2 are expecting a CustomList2(Of Parent), but I'd like to pass a Customlist2(Of Child) to it. 我知道DoSomething2上的类型参数期望使用CustomList2(Of Parent),但是我想将Customlist2(Of Child)传递给它。 I can get this to work with an interface that uses covariance. 我可以将其与使用协方差的接口一起使用。 Using an interface does not allow me toe call methods, such as CustomList2.MyCustomerList2Method. 使用接口不允许我调用诸如CustomList2.MyCustomerList2Method之类的方法。

This is a simplified example Could anyone provide some insight? 这是一个简化的示例,谁能提供一些见解?

Try adding second generic type parameter to your second method: 尝试在第二个方法中添加第二个泛型类型参数:

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

When it looks like that, you can call it like this: 看起来像这样时,您可以这样称呼它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM