繁体   English   中英

工厂返回泛型的实现

[英]Factory to return an implementation of 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始终为null之后的服务。

我怀疑问题是TEntity作为Car传递,而VehicleService被实现为IMovebale。 但是只是无法理解该怎么做,甚至有可能吗?

提前致谢。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM