如何用存储库模式问题解决这个泛型?

时间:2009-09-30 00:17:26

标签: 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 class Repository:IRepository

2-公共类CustomerRepository:Repository,ICustomerRepository

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

你可以帮我解决一下吗?

2 个答案:

答案 0 :(得分:5)

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

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

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

编辑为Reposistory

的实施添加类型约束

答案 1 :(得分:2)

在实现通用接口时,还需要提供通用接口类型规范。将这两行更改为:

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

public class CustomerRepository : Repository<ICustomer, int /*TID type*/>, ICustomerRepository
{
     // ...