【问题标题】:Cannot implicitly convert type of IEnumerable<T> to IEnumerable<T>无法将 IEnumerable<T> 的类型隐式转换为 IEnumerable<T>
【发布时间】:2015-05-18 01:46:04
【问题描述】:

考虑以下代码:

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 的行导致编译错误。

无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(您是否缺少演员表?)

为什么当它们是相同类型时需要隐式转换?为什么一个是命名空间而另一个不是?

谢谢!

【问题讨论】:

  • 您在不同的命名空间中有两种不同类型的同名 (Employee)。查看您的代码库是否缺少命名空间声明或意外重新定义的类。

标签: c# generics


【解决方案1】:

您使用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&lt;EmployeeClass&gt; 不能转换为IEnumerable&lt;EmployeeGenericParameter&gt;,因为EmployeeGenericParameter 可以是int 或其他任何东西。

【讨论】:

  • 啊,我明白我做错了什么。那么解决这个问题的唯一方法是返回吗?我希望避免演员表。公共 IEnumerable GetData(DataStore dataStore) { return (IEnumerable)dataStore.Employees; }
  • @rkrauter 是的,您应该使用显式强制转换,因为它可能在运行时失败。编译器不会通过静默插入可能失败转换来承担该责任,您应该明确承担该责任。
【解决方案2】:

您已经创建了Employee 类型的两个不同定义。一个作为普通类,另一个作为GetData 方法的通用参数。

这很容易解决。只需将泛型参数从GetData 方法移动到IFinder 接口本身。以下是你应该如何定义你的接口:

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

现在EmployeeFinder 可以像这样实现:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多