简体   繁体   English

为什么 C# 编译器允许嵌套范围内的重复变量?

[英]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.

相关问题 为什么c#编译器允许返回值类型和变量类型的错误匹配? - Why does c# compiler allow incorrect match of return value type and variable type? 为什么C#编译器允许空枚举? - Why does the C# compiler allow empty enums? 为什么 C# 编译器允许使用 Linq 而不是使用括号执行强制转换? - Why does the C# compiler allow a cast to be performed with Linq but not with parentheses? 为什么C#编译器会对这个嵌套的LINQ查询感到厌烦? - Why does the C# compiler go mad on this nested LINQ query? 如果调用ToList或ToArray,为什么C#编译器允许在表达式树中使用动态操作 - Why does C# compiler allow use of a dynamic operation in expression tree if ToList or ToArray is called 为什么C#编译器允许在IEnumerable <T>和TAlmostAnything之间进行显式转换? - Why does the C# compiler allow an explicit cast between IEnumerable<T> and TAlmostAnything? 为什么零长度堆栈分配使 C# 编译器乐于允许条件堆栈分配? - Why does a zero-length stackalloc make the C# compiler happy to allow conditional stackallocs? 为什么C#编译器会在此代码上崩溃? - Why does the C# compiler crash on this code? 为什么C#允许异构IList - Why does C# allow heterogeneous IList 为什么 C# 不允许泛型属性? - Why does C# not allow generic properties?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM