开发者

generic types polymorphism

public class A {}

public class B : A {}

now what the best way to get this working

List<A> a;
List<B> b = new List<B>();
开发者_JS百科a = b; // throw Cannot convert List<B> to List<A>

Thank you


The List<T> type doesn't support covariance, so you can't assign a List<B> directly to a List<A> even though B itself is directly assignable to A. You'll need to do a pass through list b, converting and adding the items into list a as you go. The ConvertAll method is a convenient way to do this:

List<B> b = new List<B>();
// ...
List<A> a = b.ConvertAll(x => (A)x);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜