转换列表&LT; DerivedClass&GT;列出&LT;&的BaseClass GT; [英] Convert List<DerivedClass> to List<BaseClass>
本文介绍了转换列表&LT; DerivedClass&GT;列出&LT;&的BaseClass GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
虽然我们可以从基类/接口继承,我们为什么不能声明列表与LT;&GT;
使用相同的类/接口?
While we can inherit from base class/interface, why can't we declare a List<>
using same class/interface?
interface A
{ }
class B : A
{ }
class C : B
{ }
class Test
{
static void Main(string[] args)
{
A a = new C(); // OK
List<A> listOfA = new List<C>(); // compiler Error
}
}
有没有办法解决?
Is there a way around?
推荐答案
,使这项工作的方式是遍历列表,并投中的元素。这可以使用ConvertAll来完成:
The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
您也可以使用LINQ的:
You could also use Linq:
List<A> listOfA = new List<C>().Cast<A>().ToList();
这篇关于转换列表&LT; DerivedClass&GT;列出&LT;&的BaseClass GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文