简体   繁体   English

c#for-loop和Click Event Handler

[英]c# for-loop and Click Event Handler

How do I use one individual event handler per iteration, without hard coding the functions? 如何在每次迭代中使用一个单独的事件处理程序,而无需对函数进行硬编码?

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());
}

You need to copy your iterator into a local variable for the delegate to capture it correctly: 您需要将迭代器复制到局部变量中,以便委托正确捕获它:

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     
}

In you original piece of code, the delegate says "return me the current value of the variable", which is 100. Not: "the value when it was created". 在原始代码段中,代理人说“返回变量的当前值”,即100。不是:“创建时的值”。 Read up on closures to get an in depth explanation of this. 阅读关闭以获得对此的深入解释。 I'd recommend Jon Skeets C# in depth. 我会推荐Jon Skeets C#。

In c# 5.0 this was changed for the foreach loop, not the for i; 在c#5.0中,这对于foreach循环而言是改变的,而不是for i; one though. 一个虽然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM