據(jù)我了解,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循環(huán)for (int i = 0; i < Map.Count; i++){ Position Location = Map[i]; Location = Location + Random(); Plot(Location); i = Location;}來自C ++背景,我將foreach視為for循環(huán)的替代方法。但是由于上述限制,我通常會轉而使用for循環(huán)。我很好奇,使迭代器不變的背后原理是什么?編輯:這個問題更多是一個好奇問題,而不是編碼問題。我感謝編碼答案,但無法將其標記為答案。另外,上面的示例過于簡化。這是我想做的一個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迭代器是不可變的感興趣。
- 3 回答
- 0 關注
- 534 瀏覽
添加回答
舉報
0/150
提交
取消