c# - 工厂返回 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 之后的服务始终为空。
我怀疑问题是 TEntity 是作为 Car 传递的,而 VehicleService 是作为 IMovebale 实现的。但是我无法理解如何做到这一点,或者甚至有可能吗?
提前致谢。
解决方案
您需要通过关键字将TEntity
泛型类型标记Service
为逆变in
,并使用基接口而不是基抽象类,然后转换为泛型基类型将起作用:
public interface Service<in TEntity>
{
void PerformService(TEntity t);
}
推荐阅读
- powershell - 如何搜索特定文件名,然后使用 PowerShell 将该文件之后的所有文件移动到另一个文件夹
- nginx - Nginx Ingress 控制器抛出 400 Bad Request 错误
- python - django 模板循环两个查询集
- neo4j - 如何使用 APOC 在 Neo4j 中编写更高效的导入查询
- python - Python - 基于字符串匹配减少数据框字段的值
- python - 将 DataFrame 的最后 n 行添加到新列中
- android - 以编程方式设置 ImageView 的边距和其他布局属性
- ruby - 黄瓜。如何在 RubyMine 中为 RSpec 断言启用代码完成
- python - 网页抓取。列而不是行
- laravel - 502 错误网关 nginx/1.17.10 Laravel