本文介绍了展开循环有效,for 循环无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我不明白的行为.虽然展开的循环工作正常!!!循环抛出 IndexOutOfRangeExceptions.调试显示有 0..9 个 teamButtons 和 0..9 张卡片 c[i].:(

I have some behaviour that I do not understand. While the unrolled loop works fine!!! The loop throws IndexOutOfRangeExceptions. Debugging shows that there 0..9 teamButtons and 0..9 cards 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]); });
    }
}

推荐答案

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

You're capturing the variable i in your lambda expression. When that lambda expression is executed, it will use the "current" value of i - which will always be 9. You want to capture a copy of the variable... which you can do be introducing a new variable in the loop:

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

这篇关于展开循环有效,for 循环无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:47