继承需要存储子类特定数据的数组的最佳方法是什么?

Luk*_*uke 2 c# oop inheritance covariance contravariance

我正在尝试设置类似于以下内容的继承层次结构:

abstract class Vehicle
{
  public string Name;
  public List<Axle> Axles;
}

class Motorcycle : Vehicle
{
}

class Car : Vehicle
{
}

abstract class Axle
{
  public int Length;
  public void Turn(int numTurns) { ... }
}

class MotorcycleAxle : Axle
{
  public bool WheelAttached;
}

class CarAxle : Axle
{
  public bool LeftWheelAttached;
  public bool RightWheelAttached;
}
Run Code Online (Sandbox Code Playgroud)

我想只在Motorcycle对象的Axles数组中存储MotorcycleAxle对象,在Car对象的Axles数组中存储CarAxle对象.问题是没有办法覆盖子类中的数组来强制一个或另一个.理想情况下,以下内容对摩托车类有效:

class Motorcycle : Vehicle
{
  public override List<MotorcycleAxle> Axles;
}
Run Code Online (Sandbox Code Playgroud)

但是当覆盖时类型必须匹配.我该如何支持这种架构?在Axles成员访问的任何地方,我是否只需要进行大量的运行时类型检查和转换?我不喜欢添加运行时类型检查,因为你开始失去强类型和多态的好处.在这种情况下必须至少进行一些运行时检查,因为WheelAttached和Left/RightWheelAttached属性取决于类型,但我想最小化它们.

Lar*_*ens 5

使用更多泛型

abstract class Vehicle<T> where T : Axle
{
  public string Name;
  public List<T> Axles;
}

class Motorcycle : Vehicle<MotorcycleAxle>
{
}

class Car : Vehicle<CarAxle>
{
}

abstract class Axle
{
  public int Length;
  public void Turn(int numTurns) { ... }
}

class MotorcycleAxle : Axle
{
  public bool WheelAttached;
}

class CarAxle : Axle
{
  public bool LeftWheelAttached;
  public bool RightWheelAttached;
}
Run Code Online (Sandbox Code Playgroud)