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);
加载中,请稍侯......
精彩评论