【问题标题】:Specific generic interfaces特定的通用接口
【发布时间】:2011-01-22 19:57:35
【问题描述】:

我正在重构我所有的各种类型的存储库接口。它们中的大多数都包含非常相似的方法,例如添加、更新,但有些具有仅对特定类型有意义的方法。这是一个最佳实践问题。

我考虑过使用泛型来解决问题。

 public interface IRepository<T>
 {
      T Get(int id);
      void Add(T x);
 }

但现在是具体的方法。我当然可以“子类化”接口,但我并没有比以前更好。我会有这样的代码:

 IUserRepository<User> users;

如果我可以有多个约束,例如:

 public partial interface IRepository<T>
 {
      T Get(int id);
      void Add(T x);
 }

 public partial interface IRepository<T> where T: User
 {
      T Get(Guid id);
 }

 public partial interface IRepository<T> where T: Order
 {
      T Get(string hash);
 }

但是编译器抱怨继承冲突。另一种方法是限制方法:

 public partial interface IRepository<T>
 {
      T Get(int id);
      void Add(T x);

      T Get(Guid id) where T: User;
      T Get(string hash) where T: Order;
 }

但这并不是这些工作的方式。编译器不了解我的意图,当然希望在方法上定义类型。

现在我只有抛出 NotImplemented 的方法。丑陋。

我正在寻找一个能让我自暴自弃的解决方案。

【问题讨论】:

    标签: c# generics interface repository-pattern


    【解决方案1】:
    public interface IRepository<TEntity, TId>
     {
          TEntity Get(TId id);
          void Add(T x);
     }
    
    public class UserRepository : IRepository<User, Guid>
    {
        public User Get( Guid id ) 
        {
            // ...
        }
    
        public void Add( User entity) 
        {
            // ...
        }
    }
    
    public class OrderRepository : IRepository<Order, string> 
    {
        //...
    }
    

    【讨论】:

    • 我认为定义方法是无意的。还有其他想法吗?
    • 不完美。我可以实现没有任何意义的 IRepository 。另外,这将是一个很长的类型列表。因此,出于这个原因,我实际上更喜欢“子接口”作为 IUserRepository : IRepository.
    【解决方案2】:

    以下是我对类似问题的看法:

    Advantage of creating a generic repository vs. specific repository for each object?

    要点是域通常不能被概括,需要另一种方法。我给出了一个使用特定领域接口但使用通用基类的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      相关资源
      最近更新 更多