[英]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.