如何将对象列表转换为对象在VB.net中实现的接口列表?

the*_*tgt 6 .net vb.net

我在VB.net工作并有一个Class,Foo,它实现了一个接口,IBar.我有一个Foo列表,但我需要将一个IBar列表传递给一个函数,但即使我使用DirectCast,我仍然会出现转换错误.我的代码是

Class Foo
    Implements IBar
End Class

Interface IBar
End Interface

Sub DoIt(ByVal l As List(Of IBar))
End Sub

Sub Main()
    Dim FooList As New List(Of Foo)
    DoIt(FooList)
End Sub

Sub Main2()
    Dim FooList As New List(Of Foo)
    DoIt(DirectCast(FooList, List(Of IBar)))
End Sub

Sub MainWorks()
    Dim FooList As New List(Of Foo)
    Dim IBarList As New List(Of IBar)

    For Each f As Foo In FooList
        IBarList.Add(f)
    Next

    DoIt(DirectCast(IBarList, List(Of IBar)))
    DoIt(IBarList)
End Sub
Run Code Online (Sandbox Code Playgroud)

在主要和主要2我得到

Value of type 'System.Collections.Generic.List(Of FreezePod.Pod.Foo)' cannot be converted to 'System.Collections.Generic.List(Of FreezePod.Pod.IBar)'.
Run Code Online (Sandbox Code Playgroud)

MainWorks可以工作,但是在我想要调用此函数的任何地方都必须这样做是非常烦人和低效的.

pan*_*ral 5

问题是像List(Of T)这样的泛型类型不会转换为其他List(Of U),即使转换被保证是安全的.VS2010提供了帮助,当然,这对你现在并没有什么帮助.

正如我认为在链接的线程中也建议,如果DoIt可以采用IEnumerable的IBar而不是列表,你可以这样做:

DoIt(FooList.Cast(Of IBar))
Run Code Online (Sandbox Code Playgroud)

或者如果你真的需要一个列表(并且可以承担管理费用),你可以获得一个列表:

DoIt(FooList.Cast(Of IBar).ToList)
Run Code Online (Sandbox Code Playgroud)


小智 2

添加此解决方案作为另一个答案,这应该可以满足您的要求。

Sub DoIt(Of T As IBar)(ByVal l As List(Of T))
End Sub
Run Code Online (Sandbox Code Playgroud)

使用泛型定义子。