c# for-loop 和 Click 事件处理程序

c# for-loop and Click Event Handler

如何在每次迭代中使用一个单独的事件处理程序,而不对函数进行硬编码?

for (int i = 0; i < 100; i++)
{
        //other code
        PictureBox listItem = new PictureBox();
        listItem.Click += new EventHandler((sender2, e2) => ListItemClicked(i));
        //other code     
}

private void ListItemClicked(int index)
{
    MessageBox.Show(index.ToString());
}

您需要将迭代器复制到局部变量中以便委托正确捕获它:

for (int i = 0; i < 100; i++)
{
        var idx = i;
        //other code
        PictureBox listItem = new PictureBox();
        listItem.Click += new EventHandler((sender2, e2) => ListItemClicked(idx));
        //other code     
}

在您的原始代码中,代表说 "return me the current value of the variable",即 100。不是:"the value when it was created"。 阅读闭包以获得对此的深入解释。我推荐深度学习 Jon Skeets C#。

在 c# 5.0 中,这已针对 foreach 循环进行了更改,而不是 for i; 循环。