我已经实现了一个车辆服务,负责为汽车和卡车提供服务:
public interface IVehicleService
{
void ServiceVehicle(Vehicle vehicle);
}
public class CarService : IVehicleService
{
void ServiceVehicle(Vehicle vehicle)
{
if (!(vehicle is Car))
throw new Exception("This service only services cars")
//logic to service the car goes here
}
}
我还有一个车辆服务工厂,负责根据传入到工厂方法的车辆类型创建车辆服务:
public class VehicleServiceFactory
{
public IVehicleService GetVehicleService(Vehicle vehicle)
{
if (vehicle is Car)
{
return new CarService();
}
if (vehicle is Truck)
{
return new TruckService();
}
throw new NotSupportedException("Vehicle not supported");
}
}
我遇到的问题出在
CarService.ServiceVehicle
方法上。它接收一个Vehicle
,但理想情况下应该接收一个Car
,因为它知道只会为汽车提供服务。所以我决定更新这个实现,改用泛型:public interface IVehicleService<T> where T : Vehicle
{
void ServiceVehicle(T vehicle);
}
public class CarService : IVehicleService<Car>
{
void ServiceVehicle(Car vehicle)
{
//this is better as we no longer need to check if vehicle is a car
//logic to service the car goes here
}
}
public class VehicleServiceFactory
{
public IVehicleService<T> GetVehicleService<T>(T vehicle) where T : Vehicle
{
if (vehicle is Car)
{
return new CarService() as IVehicleService<T>;
}
if (vehicle is Truck)
{
return new TruckService() as IVehicleService<T>;
}
throw new NotSupportedException("Vehicle not supported");
}
}
我目前遇到的问题是在调用以下工厂时:
var factory = new VehicleServiceFactory();
Vehicle vehicle = GetVehicle();
var vehicleService = factory.GetVehicleService(vehicle); // this returns null!
vehicleService.ServiceVehicle(vehicle);
GetVehicleService
返回 null
,我猜这是因为我将基础类型 Vehicle
传递给了此方法,所以 T
将被解析为 Vehicle
,而从实现 IVehicleService<Car>
的 CarService
转换为有效返回类型 IVehicleService<Vehicle>
是不可能的(如果我错了,请纠正我)。希望能得到一些解决此问题的指导。
CarService
转换为它,也可以将TruckService
转换为它,这是有充分理由的。简单地说,IVehicleService<Car>
不是IVehicleService<Vehicle>
。 - juharrVehicle
,要么被隐式转换为Vehicle
。 - juharras
。这样做会导致神秘的空引用异常,就像这样。如果你想表达“这个东西确实是这种类型”,那么就直接将其转换 - 至少当它失败时,你会在发生错误的地方得到一个无效的转换异常,而不是在不同位置难以调试的空引用异常。 - Philip Kendall