为什么我不能在 foreach 中修改循环变量? [英] Why can't I modify the loop variable in a foreach?
问题描述
为什么 foreach
循环是只读循环?造成这种情况的原因是什么?
我不确定您所说的只读循环"究竟是什么意思,但我猜您想知道为什么这不能编译:
int[] ints = { 1, 2, 3 };foreach (int x in int){x = 4;}
以上代码会出现如下编译错误:
<前>无法分配给x",因为它是foreach 迭代变量"为什么不允许这样做?尝试分配给它可能不会做你想做的 - 它不会修改原始集合的内容.这是因为变量 x 不是对列表中元素的引用——它是一个副本.为了避免人们编写错误代码,编译器不允许这样做.
Why is a foreach
loop a read only loop? What reasons are there for this?
I'm not sure exactly what you mean by a "readonly loop" but I'm guessing that you want to know why this doesn't compile:
int[] ints = { 1, 2, 3 };
foreach (int x in ints)
{
x = 4;
}
The above code will give the following compile error:
Cannot assign to 'x' because it is a 'foreach iteration variable'
Why is this disallowed? Trying to assigning to it probably wouldn't do what you want - it wouldn't modify the contents of the original collection. This is because the variable x is not a reference to the elements in the list - it is a copy. To avoid people writing buggy code, the compiler disallows this.
这篇关于为什么我不能在 foreach 中修改循环变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!