小编mas*_*eef的帖子

为什么 C# 编译器允许在嵌套作用域中存在重复变量?

从历史上看,在 .Net 中开发时,我无法在嵌套范围内重复变量的名称。但是,最近将 Visual Studio 2019 更新到版本 16.4.2 后,我注意到变量名称可以在嵌套作用域中重复。

例如:

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
Run Code Online (Sandbox Code Playgroud)

https://dotnetfiddle.net/h85BK4

为什么突然允许这样做?

后续问题:如果这是一个新的语言“功能”,是否有办法将 Visual Studio 配置为在嵌套范围内重复变量时继续中断?

c# .net-core visual-studio-2019

18
推荐指数
1
解决办法
350
查看次数

标签 统计

.net-core ×1

c# ×1

visual-studio-2019 ×1