问题
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