gpt4 book ai didi

C# 从工厂返回通用接口(interface)

转载 作者:太空狗 更新时间:2023-10-30 00:23:00 26 4
gpt4 key购买 nike

我实现了一个车辆服务,负责为汽车和卡车等车辆提供服务:

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");
}

}

如有任何建议,我们将不胜感激。

最佳答案

简单地将服务转换为接口(interface):

return new CarService() as IVehicleService<T>;

知道 T 是汽车,但编译器不知道,它不够智能,无法遵循方法逻辑,也不是本应如此;就编译器所知,T 可以是任何东西,只要它是 Vehicle。您需要告诉编译器,“嘿,我知道我在做什么,TCar 实际上是同一类型。”

关于C# 从工厂返回通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47000127/

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