如何有选择地只实现接口的一部分

How to selectively implement only one part of the interface

我是存储库模式的新手,并试图了解它是如何实现的 implement.For 示例 假设我有一个 class 和 2 个类似这样的接口。 并希望实现某些特定方法,而不是全部。(在 UserRepository 上)。

我怎样才能做到这一点。

public interface IRepository<T>
    {
        #region operations

        List<T>  GetAll();
        void Update(T user);
        void Delete(T user);
        void Add(T user);
        T FindById(int id);
       #endregion

        #region operations async

        List<T> GetAllAsync();
        void UpdateAsync(T user);
        void DeleteAsync(T user);
        void AddAsync(T user);
        T FindByIdAsync(int id);

        #endregion

    }

IUserRepository

 interface IUserRepository
    {
        int GetUserCount();
        int GetUserType();
        int GetUserPaged();
        int GetUserStars();
    }

用户存储库

public class UserRepository:IRepository<User>,IUserRepository
{
    public List<User> GetAllAsync()
    {
        throw new NotImplementedException();
    }

   public int GetUserCount()
   {

       return 1;
   }
}

我是否应该重新创建包含这 2 个方法的新接口?或者有没有更好的方法。

您不能选择性地选择要实现接口的哪些部分。您唯一的选择是将这些方法拆分为独立的接口,但请记住,您仍然可以在有意义的情况下继承接口,例如:

public interface IReadRepository<T>
{
    T Get(int id);
}

public interface IWriteRepository<T> : IReadRepository<T>
{
    void Add(T entity);
}

例如,这样,您的 class 只能实现 IReadRepository,因此只需要实现其中一种方法。

编辑:

您还可以显式实现接口,然后选择公开哪些方法;但是我怀疑你实际上并不想真正实现接口中的所有方法(我指的是真正的实现),如果你让它们抛出类似 NotImplementedException 的东西,将违反 Liskov 替换原则...