【发布时间】:2014-03-02 12:27:49
【问题描述】:
在我的心智模型中,for 内部定义的计数器变量变为私有,因为它无法从外部访问,如下所示。
for (int x = 0; x < 2; x++) ;
//Console.WriteLine(x); x does not exist in the current context
当我如下声明相同的变量时,我的困惑发生了,
for (int x = 0; x < 2; x++) ;
//Console.WriteLine(x); x does not exist in the current context, but why cannot I declare
//int x = 1;
为什么编译器不允许我声明一个与另一个不可访问变量同名的变量?这对我来说没有意义。 :-)
比较一下比较容易混淆
{
int x = 1;
}
{
int x = 2;
}
这是编译器允许的。但以下两种都是不允许的。
static void Foo()
{
int x = 1;
{ int x = 2; }
}
static void Bar()
{
{ int x = 2; }
int x = 3;
}
【问题讨论】:
-
这在C# Variable Scoping中有解释。
标签: c#