這可以在for循環中完成嗎?for循環中的事件處理程序的匿名方法
TickEventArgs targs1 = new TickEventArgs(lbl1_up_time, _elapsedTime_up1);
timer_up1.Tick += (sender, e) => Tick(targs1);
TickEventArgs targs2 = new TickEventArgs(lbl2_up_time, _elapsedTime_up2);
timer_up2.Tick += (sender, e) => Tick(targs2);
TickEventArgs targs3 = new TickEventArgs(lbl3_up_time, _elapsedTime_up3);
timer_up3.Tick += (sender, e) => Tick(targs3);
TickEventArgs targs4 = new TickEventArgs(lbl4_up_time, _elapsedTime_up4);
timer_up4.Tick += (sender, e) => Tick(targs4);
TickEventArgs targs5 = new TickEventArgs(lbl5_up_time, _elapsedTime_up5);
timer_up5.Tick += (sender, e) => Tick(targs5);
這不工作,因爲我是出界(5)
targs[0] = new TickEventArgs(lbl1_up_time, _elapsedTime_up1);
targs[1] = new TickEventArgs(lbl2_up_time, _elapsedTime_up2);
targs[2] = new TickEventArgs(lbl3_up_time, _elapsedTime_up3);
targs[3] = new TickEventArgs(lbl4_up_time, _elapsedTime_up4);
targs[4] = new TickEventArgs(lbl5_up_time, _elapsedTime_up5);
timers[0] = timer_up1;
timers[1] = timer_up2;
timers[2] = timer_up3;
timers[3] = timer_up4;
timers[4] = timer_up5;
int i = 0;
for (i = 0; i <= 4; i++)
{
timers[i].Tick += (sender, e) => Tick(targs[i]);
}
這是從λ表達式來; 「我」是所有人共享的。當函數被執行時,它們基本上被稱爲'timers [i] .Tick + =(sender,e)=> Tick(targs [5])''。聲明一個本地'int locali = i',並用它代替你的行。 –
@ChrisSinclair將其作爲答案發布。 – I4V
[C#Captured Variable In Loop]的可能重複(http://stackoverflow.com/questions/271440/c-sharp-captured-variable-in-loop) – nawfal