【发布时间】:2012-05-22 04:59:04
【问题描述】:
为什么我的参数x 的行为如此不稳定?
- 示例 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));
创建此编译时错误:
当前上下文中不存在名称“x”
我所期望的。
示例 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));
产生这个编译时错误:
不能在此范围内声明名为“x”的局部变量,因为它 会给'x'赋予不同的含义,它已经在a中使用过 'child' 范围来表示其他东西
我理解这个问题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 的这些博客文章帮助我了解正在发生的事情。如果有人仍然感到困惑:
【问题讨论】:
标签: c# .net c#-4.0 lambda scope