c# - 为什么不能在嵌套的局部作用域中声明重复的变量名?

标签 c# .net

基于最近的 question ,我不明白所提供的答案。看起来你应该能够做这样的事情,因为它们的范围不重叠

static void Main()
{
  {
    int i;
  }
  int i;
}

此代码无法编译并出现以下错误:

A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else

最佳答案

我认为到目前为止,没有任何答案完全从规范中得到关键的内容。

来自第 8.5.1 节:

The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.

(强调我的。)

换句话说,“later”变量的范围包括声明之前的 block 部分 - 即它包括包含“earlier”变量的“内部” block 。

您不能在其声明之前的位置引用后面的变量 - 但它仍在范围内。

关于c# - 为什么不能在嵌套的局部作用域中声明重复的变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10843971/

相关文章:

C#检测光标是否隐藏

c# - 无法隐式转换“System.TimeSpan?”具有.HasValue条件的“System.TimeSpan”

c# - 界面及其可访问性

.net - RazorEngine vs RazorTemplates vs RazorMachine

c# - 使用 LINQ 的 SQL 表行总和?

.net - 2(3)关于T4模板,获取正在处理的主文件名,能够结束处理的问题?

c# - 从类型的字符串表示中获取 List(T)

c# - 以可持续的方式使用 azure 进行 transient 故障处理

c# - 通过选定的标签过滤文档列表

.net - 设置仅在从 Visual Studio 而非构建服务器构建项目时执行的构建步骤