2010-06-17 70 views
8

當我看到這裏Darins建議..LINQ擴展SelectMany in 3.5 vs 4.0?

IEnumerable<Process> processes = 
    new[] { "process1", "process2" } 
    .SelectMany(Process.GetProcessesByName); 

process.getprocessesbyname()

..我有點好奇,我與.NET 3.5試圖在VS2008 - 它沒有編制,除非我改變到..

IEnumerable<Process> res = 
    new string[] { "notepad", "firefox", "outlook" } 
    .SelectMany(s => Process.GetProcessesByName(s)); 

看了一些Darins答案之前,我懷疑這是我認爲是問題,當我後來得到了我的手在VS2010 with.NET 4.0 - 預期 - 原建議的工作精美。

我的問題是:從3.5到4.0發生了什麼使得這個(新語法)成爲可能?擴展方法是否已被擴展(hmm)或lambda語法的新規則還是?

+0

當你試圖編譯它在.NET 3.5中,你得到了什麼編譯器錯誤? – Jacob 2010-06-17 17:25:48

+0

@Jacob - 好點:) 方法'System.Linq.Enumerable.SelectMany 的類型參數(System.Collections.Generic.IEnumerable ,System.Func >)'不能從使用中推斷出來。嘗試明確指定類型參數。 – Moberg 2010-06-17 17:30:37

+0

酷!發生這種事時我總是很煩惱。很高興知道它已被修復:) +1 – leppie 2010-06-17 17:48:31

回答

7

看來,在C#的新版本(C#4.0與C#3.0 ...不是.NET的版本)中,委託選擇更加智能。此想法在VS2008中可用,但它在解決問題時遇到了問題當有多個重載時使用哪個版本的方法。該方法是在編譯時選擇的,所以我必須相信,這與更新後的編譯器相比,更多的是.NET版本。您可能會發現,您可以在VS2010中爲.NET 2.0編譯的解決方案使用新的重載功能。

例如,這部作品在VS2008

var ret = new[] { "Hello", "World", "!!!" }.Aggregate(Path.Combine); 
// this is the value of ret => Hello\World\!!! 
+0

好的,非常感謝:) – Moberg 2010-06-17 18:50:35