2017-08-17 56 views
1

請參閱我的下面的代碼,我試圖創建一個使用泛型的接口列表,但我需要泛型版本。因此,您知道,泛型類型可能會因列表中的每個條目而有所不同,它不僅僅是具有相同泛型類型的IFoo列表。如何創建泛型列表?

如果您需要澄清,請讓我知道。

Public Interface IFoo 

End Interface 

Public Interface IFoo(Of T) 
    Inherits IFoo 

    Function Bar(foo As T) As T 

End Interface 

Public Class Foo(Of T) 
    Implements IFoo(Of T) 

    Private ReadOnly Foos As List(Of IFoo) 

    Public Function Bar(foo As T) As T Implements IFoo(Of T).Bar 
     For Each i In Foos 
      ' Can't call Bar function from IFoo(Of T) as IFoo does not define the Bar function. 
     Next 
    End Function 
End Class 
+0

您確定要在Bar函數內調用Bar函數?! – Grim

+0

@Grim可能不是最好的例子,但是,它與我的實際場景很相似。我的問題是關於如何創建一個IFoo列表,其中泛型未知且可以變化。 –

回答

1

關於泛型類型,有你需要了解的東西是IFoo(Of String)類型的對象是從一個IFoo(Of Integer)完全不同類型,它們的共同點幾乎沒有什麼實際。

如果從IFooIFoo(Of T)繼承,那麼他們共有的唯一的事情就是IFoo

因此,如果您嘗試運行一個循環並調用它們都具有的共同方法,那麼您必須將放在IFoo之內。

此外,即使您可以做到這一點,您將如何管理參數?

For Each i In Foos 
     'Let's say you can call it from here 
     Dim Myparam As ??? 'What type is your param then ? 
     i.Bar(of <What do you put here ?>)(Myparam) 
Next