方法作用域中的命名冲突

Naming Conflict in Method Scoping

Within a method, there can only be one object of any given name. We got away with reusing the same variable names using the block level scoping of our loop control variables in an earlier example, however, an object of the same name outside of the block scope will show why that does not work. See this example showing this naming conflict:

public static void DoWork()
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
    }
    int i = 777; // Compiler error here
    Console.WriteLine(i);
}

以上来自https://www.microsoft.com/net/tutorials/csharp/getting-started/scope-accessibility,请问为什么会这样?为什么c#要这样设计,C++和Java都没有这样的。(我测试过,Java和C++没有限制)

According to Eric Lippert,这样的设计选择是为了

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.

当你重构时,这种事情会特别困扰你,看似无害的更改可能会完全改变代码的含义。

您在问题开头提到的陈述并非 100% 正确。

如果您将使用下面的代码,编译器将不会产生错误

public static void DoWork()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(i);
        }
        { 
          // adding this block will remove the compiler error, 
          // and yes you can use the same variable name in the same 
          // method but you need to help the compiler that each 
          // variable usuage is under its own block.
            int i = 777; // Not compiler error anymore
            Console.WriteLine(i);
        }
    }

你的问题上面提到的编译器错误很可能是为了防止误用变量

希望对您有所帮助