![](/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.