工厂返回泛型的实现



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

实体类

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

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

我怀疑问题是TEntity作为Car传递,而VehicleService作为IMovebale实现。但是就是无法弄清楚该怎么做,或者甚至可能吗?

提前谢谢。

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

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

最新更新