转换为列表中的特定类型

时间:2012-12-27 16:58:34

标签: c# .net list types foreach

因此,假设我们有一个名为Car的类和其他三个类(Opel,Volkswagen和Peugeot)继承Car的信息,但每个类都有一个特定的变量。

所以我创建了一个新的汽车列表,我在其中添加了这三种类型的CarOpel..etc。

Opel CarOpel = new Opel(parameters);

等...

List<Car> Cars = new List<Car>();
Car.Add(CarOpel);

等...

当我使用“foreach”语句时,如何从每个类中访问这些特定变量

foreach ( Car car in Cars )
{
      // how to convert *car* in *Opel* , *Volkswagen* or *Peugeot* to get that specific variable?
}

3 个答案:

答案 0 :(得分:8)

var opelCars = cars.OfType<Opel>()


foreach ( Opel car in cars.OfType<Opel>())
{
}

其他解决方案是使用is关键字

foreach ( Car car in cars)
{
    if(car is Opel) 
    {
        var opel = (Opel)car;
    }
}

如果您需要向下投影汽车以便做某事,则可能表明您的继承层次结构错误或您的方法不在适当的位置。它可能应该是Car类中的一个虚方法,它在派生类中被重写。另请考虑阅读访客模式。

答案 1 :(得分:3)

您必须将其强制转换为特定类型。

foreach(Car car in Cars) 
{ 
    CarOpel opel = car as CarOpel;

    if (opel != null)
    {
        //do something with Opel
    }
}

答案 2 :(得分:1)

使用isas运营商。

foreach ( Car car in Cars )
{

  if (car is Opel)
  {
   // do opel operation
    var op = (Opel)car;
  }

  if (car is Volkswagen)
  {
   // do VW operation
    var vw = (Volkswagen)car;
  }
}