public class A {}
public class B : A {}
现在什么是最好的方式来获得这方面的工作泛型类型多态性
List<A> a;
List<B> b = new List<B>();
a = b; // throw Cannot convert List<B> to List<A>
谢谢
public class A {}
public class B : A {}
现在什么是最好的方式来获得这方面的工作泛型类型多态性
List<A> a;
List<B> b = new List<B>();
a = b; // throw Cannot convert List<B> to List<A>
谢谢
的List<T>
类型不支持协方差,所以你不能直接分配给List<B>
List<A>
即使B
本身可直接分配给A
。你需要做一个通过列表b
,转换和添加项目列表a
随时随地。该ConvertAll
方法是做到这一点的快捷方法:
List<B> b = new List<B>();
// ...
List<A> a = b.ConvertAll(x => (A)x);
什么ConvertAll的行为差异(X = >(A)x)和Select(x =>(A)x)? – Proviste 2011-03-07 10:08:50
'ConvertAll'是'List
参见:http://stackoverflow.com/questions/2184551/difference-between-covariance-contra-variance – 2011-03-06 23:01:33