加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 不能在方法中使用相同的变量名

发布时间:2020-12-15 23:59:26 所属栏目:百科 来源:网络整理
导读:为什么我不能使用相同的变量名,例如方法中的索引? 为什么编译器看不到不同,何时我能清楚? 例: 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 scop
为什么我不能使用相同的变量名,例如方法中的索引?

为什么编译器看不到不同,何时我能清楚?

例:

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

The purpose of all of these rules is to prevent the class of bugs in which the reader/maintainer of the code is tricked into believing they are referring to one entity with a simple name,but are in fact accidentally referring to another entity entirely. These rules are in particular designed to prevent nasty surprises when performing what ought to be safe refactorings.

What’s The Difference,Part Two: Scope vs Declaration Space vs Lifetime

A declaration space,by contrast,is a region of program text in which no two entities are allowed to have the same name.

变量的声明空间大于其范围,以防止这些误导性情况.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读