c# - 如何解决这个通用的存储库模式问题?

标签 c# design-patterns generics repository-pattern

我从上一个问题中得到了这段代码,但它没有编译:

    public interface IEntity
{     
// Common to all Data Objects
}
public interface ICustomer : IEntity
{
     // Specific data for a customer
}
public interface IRepository<T, TID> : IDisposable where T : IEntity
{
     T Get(TID key);
     IList<T> GetAll();
     void Save (T entity);
     T Update (T entity);
     // Common data will be added here
}
public class Repository<T, TID> : IRepository
{
     // Implementation of the generic repository
}
public interface ICustomerRepository
{
     // Specific operations for the customers repository
}
public class CustomerRepository : Repository<ICustomer>, ICustomerRepository
{
     // Implementation of the specific customers repository
}

但是在这两行中:

1- 公共(public)类存储库:IRepository

2- 公共(public)类 CustomerRepository : Repository, ICustomerRepository

它给我这个错误:使用通用类型“TestApplication1.IRepository”需要“2”个类型参数

你能帮我解决吗?

最佳答案

从 Repository/IRepository 继承时需要使用两个类型参数,因为它们采用两个类型参数。也就是说,当您从 IRepository 继承时,您需要指定如下内容:

public class Repository<T, TID> : IRepository<T,TID> where T:IEntity

public class CustomerRepository : Repository<ICustomer,int>,ICustomerRepository

编辑以在 Reposistory 的实现上添加类型约束

关于c# - 如何解决这个通用的存储库模式问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1495574/

相关文章:

c# - 圈复杂度为 31,这是从哪里来的?

oop - 策略模式是对的吗?

objective-c - Grand Central Dispatch 延迟执行设计模式

c# - 如何将匿名对象指定为泛型参数?

java - 如何在java中动态声明实例的泛型类型

c# - MongoDB c# 驱动程序使用 upsert 和 updateMany

c# - 计算两个纬度和经度坐标之间的距离

c# - 如何在 Excel 2002 中将一组工作表打印为 PDF?

c++ - 在 C++ 中使用桥接模式实现 IntStack

c# - 使用接口(interface)实现约束 C# 泛型参数