How to solve this generic with repository pattern problem?

℡╲_俬逩灬. 提交于 2020-01-03 17:26:17

问题


I had this code from a previous question, but its not compiling:

    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
}

But in these 2 lines :

1- public class Repository : IRepository

2- public class CustomerRepository : Repository, ICustomerRepository

It give me this error: Using the generic type 'TestApplication1.IRepository' requires '2' type arguments

can you help me solve?


回答1:


You need to use two type arguments when inheriting from Repository/IRepository because they take take two type arguments. Namely, when you inherit from IRepository, you need to specify something like:

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

and

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

Edited to add type constraint on implementation of Reposistory




回答2:


When you are implementing a generic interface, you need to provide the generic interface type specifications as well. Change those two lines to:

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

and

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


来源:https://stackoverflow.com/questions/1495574/how-to-solve-this-generic-with-repository-pattern-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!