gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:28:17 25 4
gpt4 key购买 nike

为什么我不能使用相同的变量名,例如index 在方法中?

为什么编译器看不出差异,而我明明可以?

例子:

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.

变量的声明空间大于它的范围,以防止那些误导的情况。

关于c# - 不能在方法中使用相同的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6474927/

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