c# - 需要 'System.IndexOutOfRangeException'解决方案

标签 c# image visual-studio exception

if (Int32.Parse(strTotals) == 0 && nTotalCount != 0)
{
    nTotalCount = 0;
    for (int j = 0; j < 66; j++)
    {
        if (GameHistoryPicBox1[j].InvokeRequired)
        {
            GameHistoryPicBox1[j].BeginInvoke(new MethodInvoker(() =>
            {
                if ((j + j / 6) % 2 == 0)
                    GameHistoryPicBox1[j].Image = Properties.Resources.al1;  // Line2
                else
                    GameHistoryPicBox1[j].Image = Properties.Resources.al2;  // Line4
            }));
        }
        else
        {
            if ((j + j / 6) % 2 == 0)
                GameHistoryPicBox1[j].Image = Properties.Resources.al1;
            else
                GameHistoryPicBox1[j].Image = Properties.Resources.al2;
        }
    }
}

我一直在使用线程检查 nTotalCount 值。

如果nTotalCount 为零,那么我必须清理所有游戏图片框图像。

所以我实现了上面的代码。

不幸的是,我得到了错误:

An unhandled exception of type 'System.IndexOutOfRangeException'

在 2 号线和 4 号线上。

j 的值为 66

j 的值可能是 66 吗?

最佳答案

这是因为闭包的工作原理。您正在创建并传递给 MethodInvoker 的 lambda 表达式通过引用引用了 j 变量。因此,当这段代码正在执行时(几乎可以在任何时候执行,因为它是异步的),j 变量可以具有从 066< 的任何值。循环结束后可以是66

一个快速的解决方法是复制j:

int index = j;
GameHistoryPicBox1[index].BeginInvoke(new MethodInvoker(() =>
    {
        if ((index + index / 6) % 2 == 0)
            GameHistoryPicBox1[index].Image = Properties.Resources.al1;  // Line2
        else
            GameHistoryPicBox1[index].Image = Properties.Resources.al2;  // Line4
    }));

您可以阅读更多相关信息 here .

关于c# - 需要 'System.IndexOutOfRangeException'解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19712020/

相关文章:

C# 在屏幕上查找图像匹配

c# - 绑定(bind) dataGridView 中的未绑定(bind)列不保存单元格值

c# - 如何在 WPF 列表框中获取选中的项目?

C# 将 MySQL 结果拉入数组

c++ - 如何在 Visual Studio 2019 中全局禁用 C/C++ 编译器的弃用警告?

c - 为什么 64 位 Visual Studio C 中的 CreateWindow 在创建时会自行销毁?

html - IE 11 不显示嵌入的 base 64 图像

android - Android,对图像,视频和音频使用相同的onActivityResult

css - 使用 Body Zoom 时如何使图像不缩放

c# - 无法添加对 Outlook 2016 (Office 365) Interop (16.0.0.0) 的引用