遍历具有不同结构的类

时间:2019-08-20 14:08:17

标签: c#

我需要在HTML表中显示上述类的实例。所有对象应按speed属性排序。

TypeError: data type not understood 

表格如下:

public class Bus { public float Speed {get; set;} public string Name {get; set;}}
public class Tram { public float Speed {get; set;} public string Name {get; set;}}
public class Car { public float Speed {get; set;} public string Name {get; set;}}
public class Bike 
{ 
    public float Speed {get; set;}
    public string Name {get; set;}
    public double Height {get; set;}
    public double Width {get; set;}
}

如何遍历此对象然后显示它们?我应该实现一些接口吗? 如果所有类都具有相同的字段,那将非常容易,但是在这种情况下,Bike类具有四个属性。

1 个答案:

答案 0 :(得分:2)

在创建模型时首先确定概念的公共属性。您可以创建具有公共属性的抽象基类(在我的示例中为“ Vehicle”),然后在子类中继承:

public abstract class Vehicle
{
    public string Name { get; set; }
    public float Speed { get; set; }
}

public class Bus : Vehicle { }
public class Tram : Vehicle { }
public class Car : Vehicle { }
public class Bike : Vehicle
{
    public double Width { get; set; }
    public double Height { get; set; }
}

然后可以迭代基类类型的集合,并在处理每个实例之前对每个实例进行类型检查:

var vehicles = new List<Vehicle>
{
    new Bus { Name = "Bus", Speed = 180 },
    new Bus { Name = "Bus", Speed = 179 },
    new Bike { Name = "Bus", Speed = 180, Height = 23, Width = 32 },
    new Tram { Name = "Bus", Speed = 23 }
};

foreach (var vehicle in vehicles)
{
    // ..Output vehicle.Name & vehicle.Speed
    if (vehicle is Bike bike)
    {
        // Output bike.Height & bike.Width
    }
}