为什么赋值运算符 (=) 在 foreach
循环中无效?我使用的是 C#,但我认为该参数对于支持 foreach
的其他语言(例如 PHP)是相同的。例如,如果我这样做:
string[] sArray = new string[5];
foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
我收到错误消息,“无法分配给‘item’,因为它是‘foreach 迭代变量’。”
最佳答案
这是您的代码:
foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
这是 a rough approximation编译器对此做了什么:
using (var enumerator = sArray.GetEnumerator())
{
string item;
while (enumerator.MoveNext())
{
item = enumerator.Current;
// Your code gets put here
}
}
IEnumerator<T>.Current
属性是只读的,但这实际上与此处无关,因为您正试图分配本地 item
变量为新值。阻止你这样做的编译时检查基本上是为了保护你不会做一些不会像你预期的那样工作的事情(即改变局部变量并且对底层集合/序列没有影响)。
如果您想修改索引集合的内部结构,例如 string[]
在枚举时,传统的方法是使用 for
循环而不是 foreach
:
for (int i = 0; i < sArray.Length; ++i)
{
sArray[i] = "Some assignment.\r\n";
}
关于c# - 为什么赋值运算符 (=) 在 foreach 循环中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3549750/