简体   繁体   English

投射到列表中的特定类型

[英]Casting to a specific type within a list

So let's say we have a class named Car and three other classes (Opel , Volkswagen and Peugeot ) which inherits information from Car but in addition each class has a specific variable. 假设我们有一个名为Car的类,以及其他三个类(Opel,Volkswagen和Peugeot),它们从Car继承信息,但此外每个类都有一个特定的变量。

So I create a new List of Cars in which I add those three types CarOpel..etc. 因此,我创建了一个新的汽车列表,在其中添加了这三种类型的CarOpel..etc。

Opel CarOpel = new Opel(parameters);

etc... 等等...

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

etc... 等等...

How can I access those specific variables from each class when I use the "foreach" statement 使用“ foreach”语句时,如何从每个类访问那些特定的变量

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

?

var opelCars = cars.OfType<Opel>()


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

Other solution is to use is keyword 其他解决方案是使用is关键字

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

If you need to downcast your cars in order to do something it may suggest that your inheritance hierarchy is wrong or your method is not in the proper place. 如果您需要丢车以做某事,可能表明您的继承层次结构错误或您的方法不在正确的位置。 It probably should be a virtual method in Car class which is overridden in derived classes. 它可能应该是Car类中的一个虚方法,在派生类中将其重写。 Also consider reading about visitor pattern. 还可以考虑阅读有关访客模式的信息。

You have to cast it down to the specific type. 您必须将其转换为特定类型。

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

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

Use is or as operator. 使用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;
  }
}

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

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