据我了解,C#的foreach迭代变量是不可变的.
这意味着我不能像这样修改迭代器:
foreach (Position Location in Map)
{
//We want to fudge the position to hide the exact coordinates
Location = Location + Random(); //Compiler Error
Plot(Location);
}
Run Code Online (Sandbox Code Playgroud)
我无法直接修改迭代器变量,而是必须使用for循环
for (int i = 0; i < Map.Count; i++)
{
Position Location = Map[i];
Location = Location + Random();
Plot(Location);
i = Location;
}
Run Code Online (Sandbox Code Playgroud)
来自C++背景,我认为foreach是for循环的替代品.但是由于上述限制,我通常会回退使用for循环.
我很好奇,使迭代器不可变的原理是什么?
编辑:
这个问题更多的是一个好奇的问题,而不是一个编码问题.我很欣赏编码答案,但我不能将它们标记为答案.
此外,上面的例子过于简化了.这是我想要做的C++示例:
// The game's rules:
// - The "Laser Of Death (tm)" moves around the game board from the
// start area (index …Run Code Online (Sandbox Code Playgroud)