【发布时间】: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