我尝试使用一个简单的字符串列表的变量。我声明如下:
Dim iRows As New List(Of List(Of String))然后,我尝试将其作为参数传递给另一个方法,并将该方法定义如下:
Public Sub Import(ByVal Rows As IList(Of IList(Of String)))
For Each Row As IList(Of String) In Rows
ImportRow(Row)
Next
End Sub不幸的是,当我试图运行该代码时,我得到了以下错误,它试图将我的变量传递给我的方法。
“Unable to cast object of type 'System.Collections.Generic.List1[System.Collections.Generic.List1System.String]‘to type 'System.Collections.Generic.IList1[System.Collections.Generic.IList1System.String]'.”“用户代码未处理System.InvalidCastException
当我将方法定义更改为使用类型而不是接口时,如下所示,它起作用了。
Public Sub Import(ByVal Rows As List(Of List(Of String)))
For Each Row As IList(Of String) In Rows
ImportRow(Row)
Next
End Sub那么,以这种方式在接口中使用泛型是不可能的吗?只要我不嵌套它们,它就能正常工作。
发布于 2011-08-03 02:46:27
是的,可以创建一个IList(Of IList(Of String)) --但List(Of (List(Of String))不是。考虑一下在后一种情况下,您可以调用
listOfLists.Add(arrayOfStrings)作为字符串数组实现IList(Of String)。
基本上,这与考虑一个IList(Of Fruit)和一个List(Of Banana)是完全相同的-一串香蕉不是一个水果碗,因为你不能向它添加一个苹果。
在您的例子中,您需要创建一个List(Of IList(Of String)) --或者声明一个IList(Of List(Of String))。
现在有趣的是,由于通用协方差和逆方差,您可以将List(Of List(Of String))用作.NET 4中的IEnumerable(Of IEnumerable(Of String)) - IEnumerable(Of T)在T中是协变的。但是,IList(Of T)是不变的。
一般协方差和逆方差是一个棘手的主题。Eric Lippert有written a great deal about it -使用C#作为语言,而不是VB,但希望你仍然能理解它。
发布于 2011-08-03 02:44:52
首先像这样声明iRows:
Dim iRows As New List(Of IList(Of String))然后,当您向iRows添加一个new List(Of String)时,它将隐式地进行适当的强制转换。
发布于 2011-08-03 02:46:06
尝试以下更改:
Public Sub Import(ByVal Rows As List(Of List(Of String)))
For Each Row As List(Of String) In Rows
ImportRow(Row)
Next
End Sub似乎不需要从List转换到IList。
https://stackoverflow.com/questions/6916943
复制相似问题