c# – 不能在方法中使用相同的变量名
|
为什么我不能使用相同的变量名,例如方法中的索引?
为什么编译器看不到不同,何时我能清楚? 例: 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的“第一”索引和index_2的“第二”索引? 如果我有 private void Foo()
{
for (int index = 0; index < 10; index++)
{
}
// the runtime don't know index here
}
如果运行时不知道for循环下面的索引,为什么我们不能有另一个具有该名称的变量? 解决方法
即使范围没有,这些变量的声明空间也会重叠.检查Eric Lippert关于该主题的博客:
Simple names are not so simple
What’s The Difference,Part Two: Scope vs Declaration Space vs Lifetime
变量的声明空间大于其范围,以防止这些误导性情况. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
