方法''的类型参数不能从用法中推断出来。尝试显式指定类型参数

时间:2016-04-24 21:33:23

标签: c# linq

在做这个时

IEnumerable<Colors> c = db.Products.Where(t => t.ProductID == p.ProductID).SelectMany(s => s.Colors);
if (c.Any()) sp.color = Constructor(c);

以及稍后

private string Constructor<T>(List<T> list)
{
     //Do something
}

我收到错误

  

方法的类型参数   'Controller.Constructor(System.Collections.Generic.List)'不能   从用法推断。尝试指定类型参数   明确。

当然不正确。但我错过了什么?

2 个答案:

答案 0 :(得分:2)

Constructor<T>()方法中,您希望使用List<T>类型,但提供IEnumerable<T>的实例。

  • 将方法参数类型更改为IEnumerable<T>
  • 将查询转换为List<T>类型
IEnumerable<Colors> c =
    db
        .Products
        .Where(t => t.ProductID == p.ProductID)
        .SelectMany(s => s.Colors)
        .ToList();

if (c.Any()) sp.color = Constructor(c);

private string Constructor<T>(IEnumerable<T> list)
{
    //Do something
}

答案 1 :(得分:1)

构造函数需要具体类型(List<T>)并传递接口(IEnumerable<T>)。想象一下,在IEnumerable<T>下有类似ReadOnlyCollection<T>的东西 - 你会如何将它投射到List?你不能。因此,如果您未在构造函数中使用任何特定于列表的内容,请将签名更改为:

private string Constructor<T>(IEnumerable<T> list)
{
 //Do something
}

否则 - 通过.ToList()扩展程序将您的颜色转换为列表:

if (c.Any()) sp.color = Constructor(c.ToList());
相关问题