基于最近的 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/