【发布时间】:2017-10-29 12:23:20
【问题描述】:
我已经实现了一个 Vehicle 服务,负责维修汽车和卡车等车辆:
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
}
}
我遇到的问题是如何更新 VehicleServiceFactory 以返回车辆服务的通用版本。我尝试了以下方法,但它导致编译错误,因为它无法将 CarService 转换为通用返回类型 IVehicleService:
public class VehicleServiceFactory
{
public IVehicleService<T> GetVehicleService<T>(T vehicle) where T : Vehicle
{
if(vehicle is Car)
{
return new CarService();
}
if(vehicle is Truck)
{
return new TruckService();
}
throw new NotSupportedException("Vehicle not supported");
}
}
任何建议将不胜感激。
【问题讨论】:
标签: c# generics polymorphism