c# - 控制对从接口(interface)继承的基类中的方法的访问

标签 c#

我有一个由以下类和接口(interface)组成的基本设计:

  • 一个IRepository<TEntity>接口(interface),
  • 一个Repository<TEntity>基类,
  • 和混凝土 TenantRepository类。

“问题”

由于接口(interface)继承的所有内容根据定义都具有公共(public)访问权限,因此我可以调用 Add方法(基类)

_tenantRepository.Add(new Tenant { Name = "blah" } );

虽然我应该调用Create方法TenantRepository

_tenantRepository.Create("blah");

问题

如果我能够定义 Add 那就太好了方法 protected ,以便客户端代码无法访问该方法,但这是不允许的,因为它是接口(interface)中定义的方法并且必须具有公共(public)访问权限。

或者,我可以将这些方法命名为相同,以便我实际上重写具体类中的实现。这将阻止客户端代码调用 Repository.Add直接地。但在某些情况下,我确实想阻止客户端代码调用基类中定义的方法。

另一种选择可能是编写如下内容:

    new protected void Add(Tenant tenant)
    {

    }

但这让我颤抖(当我开始重构方法名称时它很快就会崩溃)。

有更好的方法来实现这一目标吗?


一些代码片段作为引用:

界面:

public interface IRepository<TEntity> : IDisposable where TEntity : IEntity
{
    IQueryable<TEntity> GetAll();
    void Delete(TEntity entity);
    void Add(TEntity entity);
}

基类的一小部分:

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
{
    protected IDbContext Context;

    public Repository(IDbContext context)
    {
        Context = context;
    }

    public void Add(TEntity entity)
    {
        DbSet.Add(entity);
    }

    // Left out other, for this question irrelevant, method implementations 
}

最后是TenantRepository

public class TenantRepository : Repository<Tenant>
{
    public TenantRepository(IDbContext context)
        : base(context)
    {
    }

    public Tenant Create(string tenantName)
    {
        var tenant = new Tenant
            {
                Name = tenantName,
                Guid = Guid.NewGuid().ToString()
            };

        if (Exists(tenant.Name))
        {
            throw new TenantAlreadyExistsException(tenant.Name);
        }

        Add(tenant);

        return tenant;
    }

    // Left out other, for this question irrelevant, method implementations 
}

最佳答案

一种解决方案是使 TenantRepository 不继承自您的存储库。毕竟,听起来它们有不同的功能(您想要创建而不是添加。)

如果您走这条路,Repository 将成为 TenenantRepository 类的私有(private)成员,因为只有它知道何时应调用哪些存储库方法。

关于c# - 控制对从接口(interface)继承的基类中的方法的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15052393/

相关文章:

c# - Nancy 模型绑定(bind)在 Chrome、IE 中不起作用

c# - 从 MVC 4 Web Api 返回匿名类型失败并出现序列化错误

c# - 我们可以使用 List.Except 来确认一个列表是另一个列表的子集吗

c# - c# 中类、函数、变量等的正确命名符号是什么?

c# - WS_EX_COMPOSITED causes entire app to flicker/shimmer when tab control has too many tabs

c# - 如何检测字符串中的特殊字符并修改这个特殊单词?

c# - 使用 StructureMap 注入(inject)自定义成员提供程序

c# - 在 C# 上使用 C++/CLI 的情况或优缺点是什么

c# - 根据 DTO、实体模型或其他东西验证服务层中的数据?

c# - 从 C# 调用 C 函数,传递包含指针的结构