有沒有什麼方法可以調用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(父),但是我想傳遞一個Customlist2(Of Child)給它。我可以通過使用協方差的接口來使用它。使用接口不允許我調用方法,例如CustomList2.MyCustomerList2Method。
這是一個簡化的例子任何人都可以提供一些見解?
我試圖讓你的代碼一點點更具可讀性。如果您不喜歡,請隨時恢復我的更改。 – MarcinJuraszek