Using a variable name used in a child scope

This question already has an answer here:

  • C# variable scoping: 'x' cannot be declared in this scope because it would give a different meaning to 'x' 3 answers

  • It is a design choice made by the designers of C#. It reduces potential ambiguity.

    You can use it in one of the two places, inside the if or outside, but you can only define it in one place. Otherwise, you get a compiler error, as you found.


    Something I noticed that was not noted here. This will compile:

    for (int i = 0; i < 10; i++)
    {
        int a = i * 2;
    }
    for (int i = 0; i < 5; i++)
    {
        int b = i * 2;
    }
    

    Taken together, these design decisions seem inconsistent, or at least oddly restrictive and permissive, respectively.


    As Adam Crossland said, it's a design choice - Made to make sure you (or more likely, your fellow developers) dont misunderstand the code.

    You often see private instance members prefixed with a "m_" or "_" (eg. _myVar or m_myVar) to avoid confusion..

    链接地址: http://www.djcxy.com/p/53046.html

    上一篇: 为什么C#不允许我在不同的作用域中使用相同的变量名?

    下一篇: 使用子范围中使用的变量名称