我在VB.net中工作,有一个类Foo,它实现了接口(interface)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

在Main和Main2中,我都得到了
Value of type 'System.Collections.Generic.List(Of FreezePod.Pod.Foo)' cannot be converted to 'System.Collections.Generic.List(Of FreezePod.Pod.IBar)'.

MainWorks可以工作,但是在我想调用此函数的任何地方都必须这样做,这确实很烦人且效率低下。

最佳答案

添加此解决方案作为另一个答案,这应该做您想要的。

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

使用泛型定义子。

10-07 14:25