为了账号安全,请及时绑定邮箱和手机立即绑定

为什么C#foreach语句中的Iteration变量是只读的?

为什么C#foreach语句中的Iteration变量是只读的?

C#
翻阅古今 2019-12-04 09:46:13
据我了解,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迭代器是不可变的感兴趣。
查看完整描述

3 回答

  • 3 回答
  • 0 关注
  • 496 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信