小编use*_*548的帖子

实现通用工厂方法

我已经实施了一项车辆服务,负责维修汽车和卡车等车辆:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我还有一个车辆服务工厂,负责根据传入工厂方法的车辆类型创建车辆服务:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是这个CarService.ServiceVehicle方法.它接受一个Vehicle理想情况下它应该接受一个Car …

c# generics interface factory-method

10
推荐指数
1
解决办法
1231
查看次数

C#从工厂返回通用接口

我已经实施了一项车辆服务,负责维修汽车和卡车等车辆:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我还有一个车辆服务工厂,负责根据传入工厂方法的车辆类型创建车辆服务:

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

}
Run Code Online (Sandbox Code Playgroud)

我的主要问题是具体CarService.ServiceVehicle方法.它接受一个Vehicle理想情况下它应该接受一个Car代替,因为它知道它只会服务汽车.所以我决定更新此实现以使用泛型:

public interface …
Run Code Online (Sandbox Code Playgroud)

c# generics polymorphism

4
推荐指数
1
解决办法
415
查看次数

标签 统计

c# ×2

generics ×2

factory-method ×1

interface ×1

polymorphism ×1