2010-03-02 72 views
3

我重構了各種類型的所有存儲庫接口。他們中的大多數都包含非常類似的方法,如添加,更新,但有些方法只對特定類型有意義。這是一個最佳實踐問題。特定的通用接口

我想過使用泛型來理順事情。

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。醜陋。

我正在尋找一個解決方案,讓我踢自己。

回答

6
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> 
{ 
    //... 
} 
+0

我假設定義的方法是無意的。任何其他想法,任何人? – Martin 2010-03-02 18:25:18

+0

哎呀,你是......固定的 – 2010-03-02 19:12:43

+0

不完美。我可以實現IRepository ,這是沒有任何意義的。 再加上它會是一個長型的列表。所以出於這個原因,我實際上更喜歡「subinterfacing」作爲IUserRepository:IRepository 。 – Martin 2010-03-03 10:38:14