![](/img/trans.png)
[英]Cannot implicitly convert type 'IEnumerable<T>' to 'ActionResult<IEnumerable<T>>'
[英]Cannot implicitly convert type of IEnumerable<T> to IEnumerable<T>
考虑以下代码:
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 <TestNameSpace.Employee>'隐式转换为'System.Collections.Generic.IEnumerable <Employee>'。 存在显式转换(您是否缺少演员表?)
当它们是相同类型时,为什么需要隐式转换? 为什么一个命名空间命名而另一个却没有命名空间呢?
谢谢!
您已将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
或其他任何形式。
您已经创建了两个不同的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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.