以下方案的最佳设计模式是什么
这些是我的基类:
class Vehicle
{
List<Tire> Tires
}
class Tire
{
}
这些是我的派生类:
class Truck: Vehicle
{
List<TruckTire> Tires
}
class TruckTire: Tire
{
}
问题1
我想卡车 - 轮胎指向与车辆轮胎相同的列表,但为了卡车中的轮胎 - 轮胎必须拉车辆 - 轮胎并投下它。目前这就是我正在做的事情
class Truck
{
List<TruckTires> TruckTires
{
get
{
return Base.Tires.Cast<TruckTires>().ToList();
}
set
{
base.Tires = value.Cast<Tires>().ToList()
}
}
}
这会带来额外的问题,但这并不起作用。
TruckTires.Add(new TruckTire());
因为它会调用getter但它从不调用setter。为了解决这个问题,我这样做了
List<TruckTires> _tempTruckTires = TruckTires;
_temoTruckTires.add(new TruckTire());
TruckTires = _tempTruckTires
问题2
我想通过将Vehicle传递给构造函数来实例化Truck,但是这不起作用并且将所有属性映射到基类不是一个理想的解决方案
class Truck
{
public Truck(Vehicle vehicle)
{
base = vehicle
}
}
问题3
如何将带有轮胎清单的车辆投放到带有TruckTire列表的卡车上,此时我正在这样做。
Truck truck = new Truck(vehicle);
foreach(Tire tire in Vehicle.Tires)
{
TruckTire truckTire = new TrickTire(tire);
Truck.TruckTires.Add(truckTire);
}
我甚至很难找到涵盖此内容的文章。
答案 0 :(得分:0)
对于问题2,您可能希望在Vehicle
上调用复制的基类构造函数。您需要确保Vehicle
具有合适的构造函数,该构造函数需要Vehicle
并复制相应的属性。
class Truck
{
public Truck(Vehicle vehicle)
base(vehicle)
{
}
}
对于问题1和3,您可以通过更改初始基类来避免某些演员问题。如果您为轮胎使用界面,则可以将Tire
插入Vehicle
课程和TruckTire
课程中的Truck
。但是,这确实意味着当您使用它来访问ITire
特定内容时,卡车必须将列表中的任何TruckTire
投回TruckTire
。
interface ITire {}
class Vehicle
{
List<ITire> Tires
}
class Tire : ITire
{
}
我不肯定这会为你解决所有事情,但可能值得尝试。
我想提及的最后一件事,你在TruckTires
遇到问题的原因是因为最后的ToList()
get
{
return Base.Tires.Cast<TruckTires>().ToList();
}
ToList()
获取从Cast<>()
返回的枚举,并创建一个与base.Tires
无关的新列表。你需要最终返回base.Tires
而不必重新设置属性,但是你的输入和转换问题似乎正在阻止你。
答案 1 :(得分:0)
不要在车辆中制造轮胎
List<Vehicle> Vehicles = new List<Vehicle>();
Vehicle v = new Vehicle();
v.Tires.Add(new Tire(16));
Vehicles.Add(v);
VehiTruck tr = new VehiTruck();
tr.TireTrucks.Add(new TireTruck(20, 20));
tr.TireTrucks.Add(new TireTruck(21, 21));
Debug.WriteLine(tr.TireTrucks.Count());
Vehicles.Add(tr);
foreach (Vehicle vv in Vehicles)
{
if (vv is VehiTruck)
{
VehiTruck vt = (VehiTruck)vv;
Debug.WriteLine(vt.TireTrucks.Count);
Debug.WriteLine(vt.TireTrucks[0].Size);
}
else
{
Debug.WriteLine(vv.Tires.Count);
Debug.WriteLine(vv.Tires[0].Size);
}
}
public class Tire
{
public int Size { get; set; }
public Tire(int size)
{
Size = size;
}
}
public class TireTruck : Tire
{
public int Rating { get; set; }
public TireTruck(int size, int rating) : base(size)
{
Rating = rating;
}
}
public class Vehicle
{
public List<Tire> Tires { get; } = new List<Tire>();
public Vehicle() { }
public Vehicle(Vehicle v) { }
}
public class VehiTruck : Vehicle
{
public List<TireTruck> TireTrucks { get; } = new List<TireTruck>();
public VehiTruck() { }
public VehiTruck(Vehicle v) : base(v)
{ }
}