下面的代码输出 33 而不是 012。我不明白为什么每次迭代都没有捕获一个新变量 loopScopedi 而不是捕获同一个变量。
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
{
actions [i] = () => {int loopScopedi = i; Console.Write (loopScopedi);};
}
foreach (Action a in actions) a(); // 333
但是,此代码生成 012。两者之间有什么区别?
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
{
int loopScopedi = i;
actions [i] = () => Console.Write (loopScopedi);
}
foreach (Action a in actions) a(); // 012