gpt4 book ai didi

c# - 抽象子类共有的方法,但它使用子类特定类型

转载 作者:行者123 更新时间:2023-11-30 23:33:44 26 4
gpt4 key购买 nike

我有 ElectricCarDieselCar 类,它们继承自 Vehicle。它们分别有 ElectricEngineDieselEngine

两个引擎类都有 Start 方法。最初我在两个汽车子类中都实现了 StartAllEngines(),但我发现它重复性很高,所以我想在 vehicle 基类中将其抽象。

问题是,如何在基类中定义engines的类型? dynamic是一个选项,但我感觉不太好安全使用它。

或者我不应该抽象这个方法?但是这样就违反了DRY原则。

public class Vehicle{
protected List<???Engine> engines; // What should be the type?

public void StartAllEngines (){
foreach (???Engine engine in this.engines){
engine.Start();
}
}
}

public class ElectricCar: Vehicle{
public ElectricCar(){
this.engines = List<ElectricEngine>();
}
}

public class DieselCar: Vehicle{
public DieselCar(){
this.engines = List<DieselEngine>();
}
}

public class ElectricEngine: Engine {...}
public class DieselEngine: Engine {...}

最佳答案

在带有 Engine 的基类中使用泛型参数作为约束:

public class Vehicle<TEngine> where TEngine: Engine
{
protected List<TEngine> engines = new List<TEngine>();

public void StartAllEngines (){
foreach (TEngine engine in this.engines){
engine.Start();
}
}
}

public class ElectricCar: Vehicle<ElectricEngine>
{
public ElectricCar(){
}
}

public class DieselCar: Vehicle<DieselEngine>
{
public DieselCar(){
}
}

public class ElectricEngine: Engine {...}
public class DieselEngine: Engine {...}

关于c# - 抽象子类共有的方法,但它使用子类特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com