IList 到IList
我有几节课:
class Vehicle { } class Car : Vehicle { }
我有一个派生类的列表: IList cars;
我想将列表转换为其基类,并尝试: IList baseList = cars as IList;
但我总是null
。 也
cars is IList evaluates to be false.
当然,如果我执行以下操作,我可以将项目添加到列表中:
List test = new List (); foreach ( Car car in cars ) { test.Add(car); }
我得到了我的清单,但我知道必须有更好的方法。 有什么想法吗?
使用IEnumerable
.Cast :
IList vehicles = cars.Cast ().ToList();
或者,您可以避免转换为List,具体取决于您希望如何处理源汽车列表。
这种允许你将IList
为IList
的多态性是不安全的,因为它可以让你在IList
插入一个Truck
。
您遇到的问题是C#中的协变量和逆变量有限。 在C#4.0中有一个有趣的方法,在最后描述。 然而,它在Novelocrat的答案中产生了一些与卡车问题相关的其他限制。
以下是使用Linq的几种方法:
IList list = new List (); list.Add(new Derived()); IList otherlist = new List (from item in list select item as Base); IList otherlist2 = new List (list.Select(item => item as Base));
您还可以查看Krzysztof的Cwalina文章, .NET Generics的模拟协方差
var vehicles = cars.OfType()
如果你必须一直使用IList
,那么你运气不好,上面的答案可以帮助你。 但是,如果您可以使用作为IEnumerable
的IList
,然后在目标处重新转换为IList
,那就可以了,因为IEnumerable
可以接受这种做法。
// At the source or at the model. IEnumerable list = new List(); // At the destination. IList castedList = (IList )list;
虽然,由于编译器无法强制执行这些操作,因此您必须手动确保类型和基本类型确实匹配。