[英]Factory to return an implementation of Generic
I am trying to return an implementation of generic abstract class using a factory, so that the caller doesn't need to know what the concrete type returned. 我试图使用工厂返回通用抽象类的实现,以便调用者不需要知道返回的具体类型是什么。 But failed. 但是失败了。
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);
}
The problem is the service after createService is always null. 问题是createService始终为null之后的服务。
I suspect the problem is TEntity is passed as Car, whereas the VehicleService is implemented as IMovebale. 我怀疑问题是TEntity作为Car传递,而VehicleService被实现为IMovebale。 But just can't get my head around how to do it, or is it even possible? 但是只是无法理解该怎么做,甚至有可能吗?
Thanks in advance. 提前致谢。
You need to mark TEntity
generic type of Service
as contravariant via in
keyword, and use base interface instead of base abstract class, then cast to generic base type will work: 您需要标记TEntity
泛型类型的Service
作为逆变通过in
关键字,并使用基本接口的,而不是抽象基类,然后转换为普通基类型将工作:
public interface Service<in TEntity>
{
void PerformService(TEntity t);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.