gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:49:13 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com