請注意,_src繼承IQueryable<U>
和V繼承new()
;C#Linq在方法鏈中選擇問題
我寫了下面的語句,沒有語法錯誤。
IQueryable<V> a = from s in _src where (s.Right - 1 == s.Left) select new V();
但如果我重新寫了如下,Visual Studio編輯器中的 「選擇」 抱怨錯誤
IQueryable<V> d = _src.Where(s => s.Right - 1 == s.Left).Select(s=> new V());
的錯誤是:
The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly.
Candidates are:
System.Collections.Generic.IEnumerable<V> Select<U,V>(this System.Collections.Generic.IEnumerable<U>, System.Func<U,V>) (in class Enumerable)
System.Linq.IQueryable<V> Select<U,V>(this System.Linq.IQueryable<U>, System.Linq.Expressions.Expression<System.Func<U,V>>) (in class Queryable)
誰能解釋這種現象,以及解決方案是如何解決這個錯誤?
===編輯(2010-03-16 5:35 PM)===
感謝邁克兩個。我也嘗試了一個像你這樣的簡單例子。它的工作原理,但這不適用於我的。我貼的代碼如下:
public class NSM<U, V> where U : IQueryable<U> where V : new()
{
private U _src;
public NSM(U source) { _src = source; }
public IQueryable<V> LeafNodes
{
get
{
return from s in _src where (s.Right - 1 == s.Left) select new V();
}
}
}
我想LeafNodes函數被重寫成LINQ方法鏈方法。任何想法?
感謝。第一個等同的陳述是什麼? – Gnought 2010-03-16 09:18:40
您添加的代碼將不會編譯,除非U是具有Right和Left屬性的東西。所以它不能只是'IQueryable ',除非有'where U:ILeftRight'什麼的。 – 2010-03-16 11:17:31
我想通過您的更新樣本得出結論。見下面更新的答案。感謝您提供更多信息。 – 2010-03-16 13:49:44