C# 无法隐式转换类型';System.Collections.Generic.IEnumerable<;匿名类型#1>';至';System.Collections.Generic.IEnumerable<;T>;

C# 无法隐式转换类型';System.Collections.Generic.IEnumerable<;匿名类型#1>';至';System.Collections.Generic.IEnumerable<;T>;,c#,.net,linq,generics,C#,.net,Linq,Generics,我已经定义了自己的模型类MyModel.Customer 我在使用而不是直接模型类的方法中遇到了转换问题 public IEnumerable<T> MyMethod<T>() where T : class { // my method code } public IEnumerable MyMethod(),其中T:class { //我的方法代码 } 获取运行时错误: base=(14,8):错误CS026

我已经定义了自己的模型类
MyModel.Customer

我在使用
而不是直接模型类的方法中遇到了转换问题

public IEnumerable<T> MyMethod<T>() where T : class
        {
            // my method code
        }
public IEnumerable MyMethod(),其中T:class
{
//我的方法代码
}
获取运行时错误:

base=(14,8):错误CS0266:无法隐式转换类型
“System.Collections.Generic.IEnumerable”
“System.Collections.Generic.IEnumerable”
。显式转换 存在(您是否缺少演员阵容?)


为什么会这样?有什么线索吗?

你想这样做吗:

public static IEnumerable<T> MyMethod<T>() where T : class
{
    // my method code   
    List<Customer> customers = new List<Customer>()
       {
            new Customer(), new Customer(), new Customer()
       };
    return customers;
}
公共静态IEnumerable MyMethod(),其中T:class
{
//我的方法代码
列出客户=新列表()
{
新客户(),新客户(),新客户()
};
返回客户;
}
这样不行

您应该显式强制转换集合中的每个元素

public static IEnumerable<T> MyMethod<T>() where T : class 
{
    List<T> resultList = new List<T>();   
    List<Customer> customers = new List<Customer>()
       {
            new Customer(), new Customer(), new Customer()
       };
    for(int i = 0; i < customer.Count; i++)
       resultList.Add(customers[i] as T);  // attempt to cast here
    return resultList;
}
公共静态IEnumerable MyMethod(),其中T:class
{
列表结果列表=新列表();
列出客户=新列表()
{
新客户(),新客户(),新客户()
};
对于(int i=0;i
这个错误到底发生在哪里?听起来你的方法不应该是泛型的,如果你总是要返回一系列客户…请发布实际导致错误的相关代码。这个问题标题中的错误与正文中的错误消息不匹配。是哪一个?