首页 > 解决方案 > 工厂返回 Generic 的实现

问题描述

我正在尝试使用工厂返回通用抽象类的实现,以便调用者不需要知道返回的具体类型。但是失败了。

实体类

public class Car:IMoveable    { }
public interface IMoveable    { }

服务类

public abstract class Service<TEntity>
{
   public abstract void PerformService(TEntity t);
}

public class VehicleService : Service<IMoveable>
{
     public override void PerformService(IMoveable t) {     }
}

public class DefaultService : Service<object>
{
     public override void PerformService(object t){  }
}

工厂:

public static class ServiceFactory
{
   public static Service<TEntity> CreateService<TEntity>(TEntity entity) where TEntity : class
   {
      if (typeof(IMoveable).IsAssignableFrom(typeof(TEntity)))
      {
          // run time error here as returns null
          return  new VehicleService() as Service<TEntity>;
          //compiler error
          return (Service<TEntity>) new VehicleService();
      }
      else
      {
         return new DefaultService() as Service<TEntity>;
      }
   }
}

调用代码

static void Main(string[] args)
{
   var car = new Car();
   var service = ServiceFactory.CreateService(car);
}

问题是 createService 之后的服务始终为空。

我怀疑问题是 TEntity 是作为 Car 传递的,而 VehicleService 是作为 IMovebale 实现的。但是我无法理解如何做到这一点,或者甚至有可能吗?

提前致谢。

标签: c#genericsdesign-patterns

解决方案


您需要通过关键字将TEntity泛型类型标记Service逆变in,并使用基接口而不是基抽象类,然后转换为泛型基类型将起作用:

public interface Service<in TEntity>
{
    void PerformService(TEntity t);
}

推荐阅读