【问题标题】:Unrolled Loop works, for loop does not work [duplicate]展开循环有效,for循环无效[重复]
【发布时间】:2017-03-07 13:52:00
【问题描述】:

我有一些我不理解的行为。虽然展开的循环工作正常!!!循环抛出 IndexOutOfRangeExceptions。调试显示有 0..9 个团队按钮和 0..9 个卡片 c[i]。 :(

private void Awake()
{
    InitCards();
    // This works!
    teamButtons[0].onClick.AddListener(() => SetCard(c[0]));
    teamButtons[1].onClick.AddListener(() => SetCard(c[1]));
    teamButtons[2].onClick.AddListener(() => SetCard(c[2]));

    teamButtons[3].onClick.AddListener(() => SetCard(c[3]));
    teamButtons[4].onClick.AddListener(() => SetCard(c[4]));
    teamButtons[5].onClick.AddListener(() => SetCard(c[5]));

    teamButtons[6].onClick.AddListener(() => SetCard(c[6]));
    teamButtons[7].onClick.AddListener(() => SetCard(c[7]));
    teamButtons[8].onClick.AddListener(() => SetCard(c[8]));
    // This yields an IndexOutOfRangeException
    for (int i = 0; i < 9; ++i)
    {
      teamButtons[i].onClick.AddListener(() => { SetCard(c[i]); });
    } 
}

【问题讨论】:

标签: c# unity3d


【解决方案1】:

您正在 lambda 表达式中捕获 变量 i。执行该 lambda 表达式时,它将使用 i 的“当前”值 - 始终为 9。您想要捕获变量的 副本...您可以这样做在循环中引入一个新变量:

for (int i = 0; i < teamButtons.Length; i++)
{
    int index = i;
    teamButtons[i].onClick.AddListener(() => SetCard(c[index]));
} 

【讨论】:

  • 感谢您的快速答复。这是有道理的。
  • 如果i &lt; 9i &lt; teamButtons.Length 则更好,以避免在更改长度时可能出现IndexOutOfRangeExceptions
  • @Programmer:好点,会的。
猜你喜欢
  • 2010-09-16
  • 1970-01-01
  • 2016-04-15
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 2019-03-16
  • 2011-05-16
相关资源
最近更新 更多