为什么我不能使用相同的变量名称,例如index
在方法中?不能在方法中使用相同的变量名称
为什么编译器看不到,当我清楚可以吗?
例子:
private void Foo()
{
for (int index = 0; index < 10; index++) // "first"-index
{
// I'm in no doubt, use "first"-index here
// (and only within the scope of the for loop)
}
int index = 0; // "second"-index
// I'm in no doubt, use "second"-index here
// (and below)
}
是不是因为分配是在编译时做?但是,为什么编译器为什么不能在index_1中调用“first”索引,而在index_2中调用“second”索引?
如果我有
private void Foo()
{
for (int index = 0; index < 10; index++)
{
}
// the runtime don't know index here
}
如果运行时不知道下面的for循环,我们为什么不能有一个同名的另一个变量指标?
我不知道官方的原因,但总的来说,C#团队看了一下常见的错误来源,并且在语言中使它们变得非法。另一个例子:没有fallthru switch..case语句,因为缺少的中断是允许这种语言的常见错误。 –