C#匿名函数范围

cll*_*pse 2 c# lambda anonymous-function

var foo = "bar";

new Func<String>(() => 
{
    var foo = ""; // This can't be done in C#. Why is that?

    /* In JavaScript, this is perfectly valid, since this scope (the anonymous
       function) is disconnected from the outer scope, and any variable declared
       within this scope will not affect variables in the outer scope */

})()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 12

实际上,即使在javascript中它也没有完全断开; javascript允许词法闭包 - 所以没有var,旧的值foo应该仍然可用.

区别在于javascript 选择允许您以不同的含义重新声明名称(在内部范围内).C#选择不这样做.

我觉得C#版本不容易混淆!特别是当代码(在方法中更下方)期望讨论"旧"变量时,突然它开始查看"新"变量.