私が理解しているように、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;
}
}
イテレータ i が不変であるため、C# の foreach で上記のことを行うことはできません。これは、言語における foreach の設計に固有のものだと思います (間違っている場合は訂正してください)。
foreach イテレータが不変である理由に興味があります。