我正在尝试设置类似于以下内容的继承层次结构:
abstract class Vehicle { public string Name; public ListAxles; } 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; }
我想只在Motorcycle对象的Axles数组中存储MotorcycleAxle对象,在Car对象的Axles数组中存储CarAxle对象.问题是没有办法覆盖子类中的数组来强制一个或另一个.理想情况下,以下内容对摩托车类有效:
class Motorcycle : Vehicle { public override ListAxles; }
但是当覆盖时类型必须匹配.我该如何支持这种架构?在Axles成员访问的任何地方,我是否只需要进行大量的运行时类型检查和转换?我不喜欢添加运行时类型检查,因为你开始失去强类型和多态的好处.在这种情况下必须至少进行一些运行时检查,因为WheelAttached和Left/RightWheelAttached属性取决于类型,但我想最小化它们.
使用更多泛型
abstract class Vehiclewhere T : Axle { public string Name; public List 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; }