泛型类型多态 [英] 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
推荐答案
List< T>
类型不支持协方差,所以您不能指定 List< B>即使
B
本身可以直接分配给直接转换为
列表 C> A
。你需要做一个通过列表 b
,随时转换并添加列表 a
。 ConvertAll
方法是一种便捷的方法:
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);
这篇关于泛型类型多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文