我试图使用工厂返回通用抽象类的实现,以便调用者无需知道返回的具体类型。但是失败了。
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。但是只是无法理解该怎么做,甚至有可能吗?
谢谢。
答案 0 :(得分:0)
您需要通过TEntity
关键字将Service
的{{1}}通用类型标记为contravariant,并使用基本接口代替基本抽象类,然后转换为通用基本类型将起作用:
in