【发布时间】:2012-11-29 03:26:36
【问题描述】:
我有一个接受 IEnumerable(Of IEnumerable(Of MyType)) 类型参数的方法
如果我执行以下操作:
Dim list1 as new List(Of MyType) From { obj1, obj2 }
Dim list2 as new List(Of MyType) From { obj3, obj4 }
MyMethod({ list1, list2 })
它有效。
如果我传递了List(Of List(Of MyType)),它会编译但会出现运行时错误,如下所示:
System.InvalidCastException: Unable to cast object of type
'System.Collections.Generic.List`1[System.Collections.Generic.List`1[MyType]]' to type
'System.Collections.Generic.IEnumerable`1[System.Collections.Generic.IEnumerable`1[MyType]]'
如果我传递了MyType()(),它会给出编译时错误,如下所示:
Value of type '2-dimensional array of MyType' cannot be converted to
'System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of MyType))'
我目前使用的是 .net 3.5。
这似乎是一个类似于Casting List<MyObject> to IEnumerable<MyInterface> 的问题,我听说在 .net 4 中已解决。
有什么办法可以避免这个错误吗?
【问题讨论】:
标签: c# vb.net .net-3.5 generic-collections generic-variance