据我了解,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);
}
我不能直接修改迭代器变量,而是必须使用 for 循环
for (int i = 0; i < Map.Count; i++)
{
Position Location = Map[i];
Location = Location + Random();
Plot(Location);
i = Location;
}
来自 C++ 背景,我认为 foreach 可以替代 for 循环。但是由于上述限制,我通常会回退到使用 for 循环。
我很好奇,使迭代器不可变的原因是什么?
编辑:
这个问题更多的是好奇问题,而不是编码问题。我很欣赏编码答案,但我不能将它们标记为答案。
另外,上面的例子过于简单化了。这是我想要做的 C++ 示例:
// The game's rules:
// - The "Laser Of Death (tm)" moves around the game board from the
// start area (index 0) until the end area (index BoardSize)
// - If the Laser hits a teleporter, destroy that teleporter on the
// board and move the Laser to the square where the teleporter
// points to
// - If the Laser hits a player, deal 15 damage and stop the laser.
for (int i = 0; i < BoardSize; i++)
{
if (GetItem(Board[i]) == Teleporter)
{
TeleportSquare = GetTeleportSquare(Board[i]);
SetItem(Board[i], FreeSpace);
i = TeleportSquare;
}
if (GetItem(Board[i]) == Player)
{
Player.Life -= 15;
break;
}
}
我不能在 C# 的 foreach 中执行上述操作,因为迭代器 i 是不可变的。我认为(如果我错了,请纠正我),这是特定于语言中 foreach 的设计。
我对为什么 foreach 迭代器是不可变的很感兴趣。