简体   繁体   English

在C#中,将接口列表强制转换为对象列表的推荐方法是什么?

[英]In C#, what is the recommended way to cast a List of Interface to a list of objects?

I have code that returns and array of IVehicle interface 我有返回的代码和IVehicle接口数组

  IEnumerable<IVehicle> allVehicles = GetAllVehicles();

and I know that all of these objects are Car objects. 而且我知道所有这些对象都是Car对象。 What is the right way to cast 正确的铸造方法是什么

IEnumerable<IVehicle>

to

IEnumerable<Car>

as i need to pass these into another function that requires <Enumerable<Car> 因为我需要将这些传递到另一个需要<Enumerable<Car>函数中

您可以像这样进行投射:

var allCars = allVehicles.Cast<Car>();

I'm not sure if that's actually what's needed, but it can be done using a Linq extension method as follows. 我不确定这是否是真正需要的,但是可以使用如下的Linq扩展方法来完成。

IEnumerable<Car> Cars = allVehicles.Cast<Car>();

However this will throw an exception if one of the members in allVehicles is not a Car ; 但是,如果allVehicles中的成员之一不是 Car ,这将引发异常。 if desired, this can be circumvented as follows. 如果需要的话,可以如下避免。

IEnumerable<Car> Cars = allVehicles.OfType<Car>().Cast<Car>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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