开发者

generic types polymorphism

开发者 https://www.devze.com 2023-02-15 17:11 出处:网络
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>();
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

精彩评论

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