2017-08-17 57 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