爲什麼我的參數x
表現得如此不正常?Lambda Scope Clarification
- 示例1 - 在當前上下文中不存在。
- 示例2 - 無法重複使用
x
,因爲它在「子」範圍內定義。 - 示例3 - 很好。這是我困惑的部分。也許是一個不同的「孩子」範圍?
實施例1:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
var result = list.Where(x => x < 3);
Console.Write(result.ElementAt(x));
創建該編譯時間錯誤:
The name 'x' does not exist in the current context
我期望。
實施例2:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
var result = list.Where(x => x < 3);
int x = 1;
Console.Write(result.ElementAt(x));
產生這個編譯時間錯誤:
A local variable named 'x' cannot be declared in this scope because it would give a different meaning to 'x', which is already used in a 'child' scope to denote something else
我理解的範圍界定在這個問題,Is there a reason for C#'s reuse of the variable in a foreach?回答。不過,這是我以前從未見過的。另外,它使這個問題的答案,What is the scope of a lambda variable in C#?,不完整或錯誤。
實施例3:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
List<string> stringList = new List<string> { "A", "B" };
var result = list.Where(x => x < 3);
var result2 = stringList.Where(x => x != "A");
Console.Write(result2);
產生任何錯誤。
有了接受的答案,Eric Lippert的這些博客文章幫助我包圍了發生的事情。如果有人仍然困惑:
[這裏](http://blogs.msdn.com/b/ericlippert/archive/2009/11/02 /simple-names-are-not-so-simple.aspx)是兩個相關的[鏈接](http://blogs.msdn.com/b/ericlippert/archive/2009/11/05/simple-names-are-不太簡單 - 部分two.aspx)的主題。 – Servy
[linq匿名方法(閉包)中的局部變量作用域可能的重複](http://stackoverflow.com/questions/10517964/local-variable-scope-in-linq-anonymous-method-closure) – Magnus
可能重複的[什麼是在C#lambda變量的範圍?](http://stackoverflow.com/questions/10494074/what-is-the-scope-of-a-lambda-variable-in-c) – nawfal