![](/img/trans.png)
[英]Why can't I cast base reference to a variant interface implemented by derived class?
[英]Can an interface require a base class to be implemented?
我有一个抽象的 BaseRepository 来处理基本的 CRUD 操作。
public abstract class BaseRepository
{
protected readonly IDbContextFactory<DbContext> _dbContextFactory;
public BaseRepository(IDbContextFactory<TrinityDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
}
public abstract class BaseRepository<T> : BaseRepository where T : class, IUniqueIdentifier
{
public BaseRepository(IDbContextFactory<TrinityDbContext> dbContextFactory) : base(dbContextFactory) { }
}
我创建了一个抽象的 RepoServiceBase 来将这些 CRUD 操作添加到我的服务中。
public abstract class RepoServiceBase<T> where T : class, IUniqueIdentifier
{
private readonly BaseRepository<T> _repo;
public RepoServiceBase(BaseRepository<T> repo)
{
_repo = repo;
}
}
但是在构建服务时出现以下错误:无法从 IProductRepository 转换为 BaseRepository
public class ProductService : RepoServiceBase<Product>, IProductService
{
public ProductService(IProductRepository repo) : base(repo) { }
}
有没有办法要求 IProductRepository 实现 BaseRepository?
有没有办法要求 IProductService 实现 BaseRepository?
不,你不能这样做。
但是您可以创建额外的接口来处理它。
为基础存储库创建接口:
public interface IBaseRepository
{
// methods
}
public interface IBaseRepository<T> : IBaseRepository
{
// methods
}
通过基本存储库实现这些接口:
public abstract class BaseRepository : IBaseRepository
{
protected readonly IDbContextFactory<DbContext> _dbContextFactory;
public BaseRepository(IDbContextFactory<TrinityDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
}
public abstract class BaseRepository<T> : BaseRepository, IBaseRepository<T> where T : class, IUniqueIdentifier
{
public BaseRepository(IDbContextFactory<TrinityDbContext> dbContextFactory) : base(dbContextFactory) { }
}
现在您的产品存储库应该如下所示:
public interface IProductRepository : IBaseRepository<Product>
{
// methods
}
public class ProductRepository : BaseRepository<Product>, IProductRepository
{
// implementation
}
更改RepoServiceBase
:
public abstract class RepoServiceBase<T> where T : class, IUniqueIdentifier
{
private readonly IBaseRepository<T> _repo;
public RepoServiceBase(IBaseRepository<T> repo)
{
_repo = repo;
}
}
您可以忽略IBaseRepository
接口(非通用接口),因为您期望构造函数参数中只有通用版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.