2016-04-24 81 views
1

雖然這樣一個無法根據用法推斷方法「'的類型參數。嘗試顯式指定類型參數

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

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

構造函數期望具體類型(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()); 
相關問題