[英]Why does the C# compiler allow a duplicated variable in nested scope?
Historically, when developing in .Net I could not duplicate the name of variable in nested scope.从历史上看,在 .Net 中开发时,我无法在嵌套范围内复制变量的名称。 However, after recently updating Visual Studio 2019 to version 16.4.2 I have noticed that variable names can be duplicated in nested scope.
但是,在最近将 Visual Studio 2019 更新到版本 16.4.2 后,我注意到变量名可以在嵌套范围内重复。
For example:例如:
var test = "hello";
Console.WriteLine(test);
var things = new []{"one", "two", "three"};
things.Select(test => // <- test is duplicated here, normally this breaks compilation
{
Console.WriteLine(test);
return test;
}).ToList();
// output:
// hello
// one
// two
// three
https://dotnetfiddle.net/h85BK4 https://dotnetfiddle.net/h85BK4
Why is this suddenly allowed?为什么突然允许这样做?
Follow up question: If this is a new language "feature", is there a way to configure Visual Studio to continue to break when a variable is duplicated in nested scope?后续问题:如果这是一个新的语言“功能”,是否有办法将 Visual Studio 配置为在嵌套范围内重复变量时继续中断?
这是 C# 8.0 中的一项新功能,本地函数和 lambda 参数可以隐藏外部名称。
my guess is that the select function is being compiled as static since it has no connections to the host method body.我的猜测是 select 函数被编译为静态,因为它没有连接到主机方法体。 it just prints and returns the item in question.
它只是打印并返回有问题的项目。 this does not require any access to the method and as such, it can for optimization reasons be moved out of the method body and put on its own within the global scope.
这不需要对方法的任何访问,因此,出于优化原因,它可以移出方法主体并在全局范围内单独放置。
and in this case, that test variable is its own variable and has no connections to the above test variable.在这种情况下,该测试变量是它自己的变量,与上述测试变量没有任何联系。
as for preventing this, you can't tell vs to throw an error when it occurs, you will just have manually change the variable name.至于防止这种情况,您不能告诉 vs 在发生错误时抛出错误,您只需手动更改变量名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.