【问题标题】:Interface with the method of generic type与泛型方法的接口
【发布时间】:2017-08-05 11:50:49
【问题描述】:

我有一个interface

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

我应该如何实现该方法?编译器说我不能像下面显示的那样做,因为我返回的不是通用列表

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

【问题讨论】:

  • 方法的签名意味着你可以调用例如repository.GetAll&lt;User&gt;()。你想怎么处理?

标签: c# .net inheritance interface


【解决方案1】:

Repository 设为通用接口:

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

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

【讨论】:

    【解决方案2】:

    您应该将接口存储库也定义为通用的

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

    您的 EmployeeRepository 应该按如下方式实现它

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

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 2012-03-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多