为什么赋值运算符(=)在foreach循环无效? [英] Why are assignment operators (=) invalid in a foreach loop?
问题描述
为什么赋值运算符(=)在的foreach
循环无效?我使用C#,但我会假设参数是支持的foreach
(如PHP)的其他语言的相同。例如,如果我做这样的事情:
Why are assignment operators (=) invalid in a foreach
loop? I'm using C#, but I would assume that the argument is the same for other languages that support foreach
(e.g. PHP). For example, if I do something like this:
string[] sArray = new string[5];
foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
我得到一个错误,无法分配到项,因为它是一个'foreach迭代变量'
I get an error, "Cannot assign to 'item' because it is a 'foreach iteration variable'."
推荐答案
下面的代码:
foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
下面的的粗略的估计与此编译器做什么:
Here's a rough approximation of what the compiler does with this:
using (var enumerator = sArray.GetEnumerator())
{
string item;
while (enumerator.MoveNext())
{
item = enumerator.Current;
// Your code gets put here
}
}
的
的IEnumerator< T> .Current
属性是只读的,但实际上不是与此有关,因为你正试图分配本地项目
变量为一个新值。编译时检查阻止你这样做是在基本到位,以保护你这样做是行不通的像你期望的东西(比如改变一个局部变量,其对底层集合/序列无影响)。
The IEnumerator<T>.Current
property is read-only, but that's not actually relevant here, as you are attempting to assign the local item
variable to a new value. The compile-time check preventing you from doing so is in place basically to protect you from doing something that isn't going to work like you expect (i.e., changing a local variable and having no effect on the underlying collection/sequence).
如果你想修改索引的集合的内部,如的String []
同时枚举,传统的方式是使用为
循环,而不是一个的foreach
:
If you want to modify the internals of an indexed collection such as a string[]
while enumerating, the traditional way is to use a for
loop instead of a foreach
:
for (int i = 0; i < sArray.Length; ++i)
{
sArray[i] = "Some assignment.\r\n";
}
这篇关于为什么赋值运算符(=)在foreach循环无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!