简体   繁体   中英

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>();
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM