2013-12-12 80 views
0

有沒有什麼方法可以調用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。

這是一個簡化的例子任何人都可以提供一些見解?

+0

我試圖讓你的代碼一點點更具可讀性。如果您不喜歡,請隨時恢復我的更改。 – MarcinJuraszek

回答

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))() 
+0

我已經冒險了這條路線,它的工作原理,但它使得函數調用非常漫長和繁瑣的寫作。我希望只需要傳入「集合」類型,並將集合中的泛型類型設置爲繼承Parent的任何類型。我猜這是不可能的,沒有使用反射或什麼的。 – Ted

+0

恐怕你不能在這裏通用類型推斷。 – MarcinJuraszek