我重构了各种类型的所有存储库接口。他们中的大多数都包含非常类似的方法,如添加,更新,但有些方法只对特定类型有意义。这是一个最佳实践问题。特定的通用接口
我想过使用泛型来理顺事情。
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。丑陋。
我正在寻找一个解决方案,让我踢自己。
我假设定义的方法是无意的。任何其他想法,任何人? – Martin 2010-03-02 18:25:18
哎呀,你是......固定的 – 2010-03-02 19:12:43
不完美。我可以实现IRepository,这是没有任何意义的。 再加上它会是一个长型的列表。所以出于这个原因,我实际上更喜欢“subinterfacing”作为IUserRepository:IRepository 。 –
Martin
2010-03-03 10:38:14