为什么我不能修改一个foreach循环变量? [英] Why can't I modify the loop variable in a foreach?
问题描述
为什么一个的foreach
循环只读循环?是什么原因,有这个?
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;
}
以上code将使以下编译错误:
The above code will give the following compile error:
Cannot assign to 'x' because it is a 'foreach iteration variable'
这是为什么不允许?试图分配给它可能不会做你想要的 - 它不会修改原始集合的内容。这是因为,变量x是不要在列表中的元素的引用 - 它是一个拷贝。为了避免人车写作code,编译器不允许这样。
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屋!