局部变量不能在此范围内声明[LINQ的/ Lambda表达式] [英] A local variable cannot be declared in this scope[Linq/Lambda expression]
问题描述
我在C#下面的代码片段
静态无效的主要()
{
变种数=新[] {1,2,3,4,5,6};
变种ngt5 = numbers.Where(N =将N大于5);
变种N = ngt5.First()的ToString()。
Console.WriteLine(N,数字);
}
当我编译上面的代码我收到以下错误
的局部变量命名为'N'不能在此范围
您的问题就在这里:
//在你的拉姆达你有一个N。
变种ngt5 = numbers.Where(N =将N大于5);
//和外部范围内也有一个N。
变种N = ngt5.First()的ToString()。
要理解为什么这是一个问题,考虑下面的代码:
INT N = 1000;
变种找齐= Enumerable.Range(1,1000)。凡(N =将N%2 == 0);
表达式 N%2 == 0
以上是模糊的:它 N
,我们谈论的?如果我们谈论的外的 N
,那么 N%2 == 0
是的总是正确的,因为 N
仅1000(因此找齐
将包含所有号码1到1000)。在另一方面,如果我们谈论的内的 N
,那么 N%2 == 0
将只为偶数值持有真正的 N
(和找齐
将是2,4,6 ,1000)。
要认识到的重要一点是,在lambda之外声明变量是从拉姆达的范围内使用。
INT N = 0;
行动incrementN =()=> Ñ++; //访问的外部变量
incrementN();
Console.WriteLine(N); //输出'1'
这就是为什么歧义存在,为什么它因此不允许的。
解决方案是简单地选择适合您的lambda不同的变量名; 。例如:
VAR ngt5 = numbers.Where(X => X→5);
I have following code snippet in c#
static void Main()
{
var numbers = new[] { 1, 2, 3, 4, 5, 6 };
var ngt5 = numbers.Where(n => n > 5);
var n = ngt5.First().ToString();
Console.WriteLine(n, numbers);
}
When I am compiling the above code I am getting following error
A local variable named 'n' cannot be declared in this scope
Your problem is here:
// Within your lambda you have an 'n'.
var ngt5 = numbers.Where(n => n > 5);
// And within the outer scope you also have an 'n'.
var n = ngt5.First().ToString();
To understand why this is a problem, consider the following code:
int n = 1000;
var evens = Enumerable.Range(1, 1000).Where(n => n % 2 == 0);
The expression n % 2 == 0
above is ambiguous: which n
are we talking about? If we're talking about the outer n
, then n % 2 == 0
is always true since n
is just 1000 (and therefore evens
will comprise all numbers from 1 to 1000). On the other hand, if we're talking about the inner n
, then n % 2 == 0
will only hold true for even values of n
(and evens
will be 2, 4, 6, ... 1000).
The important point to realize is that variables declared outside the lambda are accessible from within the lambda's scope.
int n = 0;
Action incrementN = () => n++; // accessing an outer variable
incrementN();
Console.WriteLine(n); // outputs '1'
This is why the ambiguity exists, and why it is therefore not allowed.
The solution is simply to pick a different variable name for your lambda; e.g.:
var ngt5 = numbers.Where(x => x > 5);
这篇关于局部变量不能在此范围内声明[LINQ的/ Lambda表达式]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!