Problem with Anonymous delegate in loop

TestForeachEventHandler.zip
   1: foreach (Test test in tests)
   2:             {
   3:                 Button button = new Button();
   4:                 button.Text = test.name;
   5:                 button.Click+=new EventHandler((object obj, EventArgs arg)=>{
   6:                     this.CreateTest(test);
   7:                 });
   8:                 this.flowLayoutPanel1.Controls.Add(button);
   9:             }

tests里有2个元素,分别为test1与test2, 程序会为每个test新建一个button, 设为button1,button2.
在button1的Click事件触发的时候,调用CreateTestFlow方法时,传递的参数会是test2而不是test1.

原因:

WTF: "Problems" with Anonymous Delegates, LINQ, Lambdas within "foreach" or "for" Loops这篇文章里的解释为:匿名委托里的test是对循环变量引用,在循环结束时该变量为最后个值,即’test2’.
如对foreach的理解相对困难的话,可以把foreach改为for,代码如下:

   1: for (int i=0;i 
    
   2: {
   3:     Button button = new Button();
   4:     button.Text = tests[i].name;
   5:     button.Click+=new EventHandler((object obj, EventArgs arg)=>{
   6:         this.CreateTest(tests[i]);
   7:     });
   8:     this.flowLayoutPanel1.Controls.Add(button);
   9: }

则此代码在运行时,会在第6行出现:ArgumentOutOfRangeException, Index was out of range.

解决方法:

在循环体里新建一变量,用来保存循环过程中的值。代码如下:

   1:  foreach (Test tes in tests)
   2:             {
   3:                 Test test = tes;
   4:                 Button button = new Button();
   5:                 button.Text = test.name;
   6:                 button.Click+=new EventHandler((object obj, EventArgs arg)=>{
   7:                     this.CreateTest(test);
   8:                 });
   9:                 this.flowLayoutPanel1.Controls.Add(button);
  10:             }

你可能感兴趣的:(Problem with Anonymous delegate in loop)