Interface with the method of generic type

时间:2017-08-05 11:50:50

标签: c# .net inheritance interface

I have an interface

interface Repository {
     ...
     List<T> GetAll<T>();
     ...
}

How should i implement that method? Compiler says that i cannot do it like show below because im returning not generic list

public class EmployeeRepository : Repository {
    ...
    public List<T> GetAll<T>() {
        List<Employee> employees = new List<Employee>();
        ...
        return employees;
}

2 个答案:

答案 0 :(得分:9)

Make Repository a generic interface:

interface Repository<T> {
        List<T> GetAll();
}

public class EmployeeRepository : Repository<Employee> {       
        public List<Employee> GetAll() {
            List<Employee> employees = new List<Employee>();
            return employees;
        }
}

答案 1 :(得分:3)

You should define interface Repository also as generic like

public interface IRepository<T> {
  List<T> GetAll();
}

and your EmployeeRepository should implement it as follows

public class EmployeeRepository : IRepository<Employee> {

  public List<Employee> GetAll() {
    List<Employee> employees = new List<Employee>();

    return employees;
  }
}