是否有任何方法可以调用MainApplication内部的Me.DoSomething2。调用DoSomething以在下面的代码中工作。
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(OfChild)。我可以将其用于使用协方差的接口。使用接口不允许我调用方法,例如CustomList2.MyCustomerList2Method.
这是一个简化的例子。有人能提供一些见解吗?
尝试在第二个方法中添加第二个泛型类型参数:
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))()