问题描述
我有以下代码(给定a,b和c生成二次函数)Func<double, double, double, Func<double, double>> funcGenerator = (a, b, c) => f => f * f * a + b * f + c;
到目前为止,很可爱.
但是,如果我尝试声明一个名为a,b,c或f的变量,Visual Studio会弹出一个"A local variable named 'f' could not be declared at this scope because it would give a different meaning to 'f' which is used in a child scope."
基本上,这失败了,我也不知道为什么,因为子作用域甚至没有任何意义.
I have the following code (generates a quadratic function given the a, b, and c)Func<double, double, double, Func<double, double>> funcGenerator = (a, b, c) => f => f * f * a + b * f + c;
Up until now, lovely.
But then, if i try to declare a variable named a, b, c or f, visual studio pops a "A local variable named 'f' could not be declared at this scope because it would give a different meaning to 'f' which is used in a child scope."
Basically, this fails, and I have no idea why, because a child scope doesn't even make any sense.
Func<double, double, double, Func<double, double>> funcGenerator =
(a, b, c) => f => f * f * a + b * f + c;
var f = 3; // Fails
var d = 3; // Fine
这是怎么回事?
推荐答案
我认为您会误解的是,关于作用域规则,声明的顺序对C#编译器无关紧要.
I think what you're misunderstanding is that the order of declarations does not matter to the C# compiler with respect to scoping rules.
此:
Func<double, double, double, Func<double, double>> funcGenerator =
(a, b, c) => f => f * f * a + b * f + c;
var f = 3;
var d = 3;
与此完全相同:
var f = 3;
Func<double, double, double, Func<double, double>> funcGenerator =
(a, b, c) => f => f * f * a + b * f + c;
var d = 3;
范围不是顺序敏感的.您有一个名为f
的局部变量,并且试图在lambda中声明另一个名为f
的变量.根据C#规范,这是非法的.
Scopes aren't order-sensitive. You have a local variable named f
, and you are trying to declare another variable named f
inside the lambda. This is illegal according to the C# spec.
具体来说,它将与lambda执行变量捕获的能力冲突.例如,此代码是合法的:
Specifically, it would conflict with the ability of lambdas to do variable capturing. For example, this code is legal:
int x = 3;
Func<int> func = () => x + 1;
这是完全合法的,执行func()
将返回4
.这就是为什么您不能在lambda中声明另一个变量x
的原因-因为lambda实际上需要能够捕获外部的x
.
This is completely legal and executing func()
will return 4
. That's why you can't declare another variable x
here inside the lambda - because the lambda actually needs to be capable of capturing the outer x
.
只需更改f
变量之一的名称即可.
Just change the name of one of the f
variables.
这篇关于当我声明与Lambda中的变量同名的变量时,C#会发疯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!