gpt4 book ai didi

c# - 如何在一个或多个 for 循环中使用现有变量?

转载 作者:可可西里 更新时间:2023-11-01 13:27:51 24 4
gpt4 key购买 nike

我正在学习 Head First C#,但我对当前的练习有点困惑。他们说:

If you declare a variable inside a for loop--for (int c = 0; ...)--then that variable's only valid inside the loop's curly brackets. So if you have two for loops that both use the variable, you'll either declare it in each loop or have one declaration outside the loop. And if the variable c is already declared outside of the loops, you can't use it in either one.

这对我来说听起来很矛盾,几乎就像是说只有在外面声明才能在外面使用,但如果在外面声明就不能使用。

那么你可以,还是不能?我尝试在两个单独的 for 循环中声明 c 并且它工作正常,但是当在 for 循环之外声明 c 时,我找不到任何方法来引用两个 for 循环内的变量 c 而它也在外部声明,无论我是否试图改变它的值(value)或不。这不是练习所必需的,我只是想吸收我遇到的每一点知识,并尝试超越 Material 。

这本书可能让我感到困惑,所以如果这不可能并且完全没有必要,请告诉我,谢谢!

最佳答案

问题是范围界定之一。阅读here有关变量作用域在 C# 中如何工作的一些详细信息。

如果一个变量在循环声明,你不能在循环内重新声明它:

:

int c = 0;
for(int c = 0; c < list.Count; c++) // Error!
{

}

确定:

外部声明,在内部使用:

int c = 0;
for(c = 0; c < list1.Count; c++)
{
}

for(c = 0; c < list2.Count; c++)
{
}

两个循环中声明:

for(int c = 0; c < list1.Count; c++)
{
}

for(int c = 0; c < list2.Count; c++)
{
}

关于c# - 如何在一个或多个 for 循环中使用现有变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4117115/

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