IList的<类型>到IList的<基本类型> [英] IList<Type> to IList<BaseType>

查看:152
本文介绍了IList的<类型>到IList的<基本类型>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几类:

class Vehicle
{
}

class Car : Vehicle
{
}

我有派生类的列表:     的IList<车>汽车;

I have a list of the derived class: IList<Car> cars;

我想在列表转换为它的基类,并曾尝试:     的IList&LT;车&GT; baseList =车作为IList的&LT;车辆取代;

I would like to convert the list to its base class, and have tried: IList<Vehicle> baseList = cars as IList<Vehicle>;

不过,我总是得到。此外

But I always get null. Also

cars is IList<Vehicle> evaluates to be false.

当然,我可以添加项目,如果我做了以下列表:

Granted, I can add the items to a list if I do the following:

List<Vehicle> test = new List<Vehicle> ();

foreach ( Car car in cars )
{
   test.Add(car);
}

和我得到我的名单,但我知道必须有一个更好的办法。 有什么想法?

And I get my list, but I know there has to be a better way. Any thoughts?

推荐答案

使用<一个href="http://msdn.microsoft.com/en-us/library/bb341406.aspx">IEnumerable<$c$c><T>.Cast

Use IEnumerable<T>.Cast :

IList<Vehicle> vehicles = cars.Cast<Vehicle>().ToList();

另外,你可能能够避免转换列表取决于您希望如何处理源汽车名单。

Alternatively, you may be able to avoid the conversion to List depending on how you wish to process the source car list.

这篇关于IList的&LT;类型&GT;到IList的&LT;基本类型&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆