c# - 无法将 IEnumerable<T> 的类型隐式转换为 IEnumerable<T>

标签 c# generics

考虑以下代码:

namespace TestNameSpace {
  public interface IFinder
  {
    IEnumerable<T> GetData<T>(DataStore dataStore);
  }

  public class EmployeeFinder : IFinder {
    public IEnumerable<Employee> GetData<Employee>(DataStore dataStore) {
        return dataStore.Employees; //*****This causes an error*****
    }
  }

  public class DataStore {
    public IEnumerable<Employee> Employees { get; set;}
  }

  public class Employee {

  }
}

我返回 dataStore.Employees 的行导致编译错误。

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<TestNameSpace.Employee>' to 'System.Collections.Generic.IEnumerable<Employee>'. An explicit conversion exists (are you missing a cast?)

为什么相同类型时需要隐式转换?为什么一个有命名空间而另一个没有?

谢谢!

最佳答案

您已经使用了Employee作为方法通用参数的名称,因此 Employee 有两种不同的含义在您的代码中。

namespace TestNameSpace {
  public interface IFinder
  {
    IEnumerable<T> GetData<T>(DataStore dataStore);
  }

  public class EmployeeFinder : IFinder {
    public IEnumerable<EmployeeGenericParameter> GetData<EmployeeGenericParameter>(DataStore dataStore) {
        return dataStore.Employees;
    }
  }

  public class DataStore {
    public IEnumerable<EmployeeClass> Employees { get; set;}
  }

  public class EmployeeClass {

  }
}

IEnumerable<EmployeeClass>无法转换为 IEnumerable<EmployeeGenericParameter>作为EmployeeGenericParameter可以是int或其他任何内容。

关于c# - 无法将 IEnumerable<T> 的类型隐式转换为 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293998/

相关文章:

java - 绑定(bind)不匹配 : type is not a valid substitute for the bounded parameter

c# - 在 C# 中遇到继承和泛型问题

java - 在 Java 中为具有类型参数的类编写平等契约

c# - 将 HttpRequestMessage 转换为 OwinRequest 并将 OwinResponse 转换为 HttpResponseMessage

C# EPPlus 合并 Excel 文件

c# - 如何在泛型类中访问 T 类型的静态属性?

C# 泛型 : does compiler creates only one specialized generic type for different reference types?

c# - 线程池会不会排队一个定时器的回调函数,有时会同时调度多个线程?

c# - “密封类中的 protected 成员”警告(单例类)

c# - 用于计数的信号量实现。当前正在运行的实例