gpt4 book ai didi

c# - for循环中声明的变量是局部变量?

转载 作者:IT王子 更新时间:2023-10-29 03:32:46 28 4
gpt4 key购买 nike

我已经使用 C# 很长时间了,但从未意识到以下几点:

 public static void Main()
{
for (int i = 0; i < 5; i++)
{

}

int i = 4; //cannot declare as 'i' is declared in child scope
int A = i; //cannot assign as 'i' does not exist in this context
}

如果它不允许我用这个名字声明一个变量,那么为什么我不能在 for block 之外使用 'i' 的值呢?

我认为 for 循环使用的迭代器变量仅在其范围内有效。

最佳答案

不允许在 for 循环中和 for 循环外定义同名变量的原因是外部作用域中的变量在内部作用域中有效。这意味着如果允许的话,for 循环中将有两个“i”变量。

参见:MSDN Scopes

具体来说:

The scope of a local variable declared in a local-variable-declaration (Section 8.5.1) is the block in which the declaration occurs.

The scope of a local variable declared in a for-initializer of a for statement (Section 8.8.3) is the for-initializer, the for-condition, the for-iterator, and the contained statement of the for statement.

还有:Local variable declarations (C# 规范第 8.5.1 节)

具体来说:

The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.

(强调我的。)

这意味着您的 for 循环中 i 的范围是 for 循环。而在 for 循环之外的 i 范围是整个 main 方法加上 for 循环。这意味着您将在循环中出现两次 i,根据上述内容,这是无效的。

不允许您执行 int A = i; 的原因是因为 int i 仅适用于 for 循环。因此它不再可以在 for 循环之外访问。

如您所见,这两个问题都是范围界定的结果;第一个问题 (int i = 4;) 将在 for 循环范围内产生两个 i 变量。而 int A = i; 会导致访问超出范围的变量。

您可以做的是将 i 声明为整个方法的作用域,然后在方法和 for 循环作用域中使用它。这将避免违反任何一条规则。

public static void Main()
{
int i;

for (i = 0; i < 5; i++)
{

}

// 'i' is only declared in the method scope now,
// no longer in the child scope -> valid.
i = 4;

// 'i' is declared in the method's scope -> valid.
int A = i;
}

编辑:

当然可以更改 C# 编译器以允许此代码非常有效地编译。毕竟这是有效的:

for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}

for (int i = 5; i > 0; i--)
{
Console.WriteLine(i);
}

但是,如果能够编写如下代码,对您的代码可读性和可维护性真的有好处吗:

public static void Main()
{
int i = 4;

for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}

for (int i = 5; i > 0; i--)
{
Console.WriteLine(i);
}

Console.WriteLine(i);
}

想想这里可能会出错,最后的i打印出来的是0还是4?现在这是一个非常小的示例,一个非常容易理解和跟踪的示例,但与用不同的名称声明外部 i 相比,它的可维护性和可读性肯定要差得多。

注意:

请注意,C# 的作用域规则不同于 C++'s scoping rules .在 C++ 中,变量仅在从声明它们的位置到 block 末尾的范围内。这将使您的代码成为 C++ 中的有效构造。

关于c# - for循环中声明的变量是局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7992332/

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