c# - 方法作用域中的命名冲突

标签 c# language-design

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.

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

关于c# - 方法作用域中的命名冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555907/

相关文章:

c# - 子任务与 WaitAll

python - "Least Astonishment"和可变默认参数

c# - If-Else 条件下的运算符

c# - 在 for/foreach 循环中声明相同的对象

language-design - 为什么在主体之后重复模块和过程名称?

java - java.util.Calendar 中的 complete() 方法

c# - C# 中的 Case 语句 block 级声明空间

c# - 值类型可以通过内联来实现吗?

c# - GitSharp 与 NGit

c# - 显示 Prism 模块内部的 Prism 模块