簡體   English   中英

接口可以要求實現基類嗎?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM