什么是最佳的方法继承一系列需要储存特定子类的数据?
-
09-06-2019 - |
题
我试图设立一个继承层次结构类似于以下内容:
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;
}
我想只存储MotorcycleAxle的对象,在一个摩托车对象的车轴阵列,并CarAxle对象在一辆汽车对象的车轴阵列。问题是没有办法替代的阵子类力量的一个或另一个。理想的情况类似于以下将是有效的摩托车等级:
class Motorcycle : Vehicle
{
public override List<MotorcycleAxle> Axles;
}
但有类型的匹配当重写。我怎么能支持这一架构?我只需要做很多的运行时间类型检查和铸造的地轴的成员访问?我不喜欢加入运行时间类型的检查,因为你开始失去对收益的强大的打字和多态性。必须有至少某些运行时检查在这种情况下由于WheelAttached和左/RightWheelAttached特性取决于这种类型,但是我想尽量减少他们。
解决方案
使用更多泛型
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;
}
其他提示
2选择的弹头脑。1使用的是仿制药:
abstract class Vehicle<TAxle> where TAxle : Axle {
public List<TAxle> Axles;
}
第二次使用的阴影-和这个假定你有的性质:
abstract class Vehicle {
public IList<Axle> Axles { get; set; }
}
class Motorcyle : Vehicle {
public new IList<MotorcycleAxle> Axles { get; set; }
}
class Car : Vehicle {
public new IList<CarAxle> Axles { get; set; }
}
void Main() {
Vehicle v = new Car();
// v.Axles is IList<Axle>
Car c = (Car) v;
// c.Axles is IList<CarAxle>
// ((Vehicle)c).Axles is IList<Axle>
的问题的阴影是,你有一个通用的清单。不幸的是,你不能约束的清单只包含CarAxle.还有,你不能投一个列表<Axle> 成列表<CarAxle> -即使有一个继承链。你必须投每个对象进入一个新的列表(虽然这变得容易得多与皇宫).
我会去泛型自己。
我问一个 类似的问题 并得到了一个更好的答案,问题是相关的C#'s支持和协逆.看到讨论的一个小小的更多信息。
不隶属于 StackOverflow