C# c闭包lambda
有人能解释一下下面的代码是怎么回事吗?为什么什么都没印出来C# c闭包lambda,c#,lambda,C#,Lambda,有人能解释一下下面的代码是怎么回事吗?为什么什么都没印出来 var actions = new Action[100]; for(int i=0;i<100;i++) { actions[i] = () => DoSomething(i); } foreach(var action in actions) { action(); } void DoSomething(int i) { if(i % 9 == 0) Console.Write
var actions = new Action[100];
for(int i=0;i<100;i++)
{
actions[i] = () => DoSomething(i);
}
foreach(var action in actions)
{
action();
}
void DoSomething(int i)
{
if(i % 9 == 0)
Console.WriteLine("{0} is a multiple of 9",i);
}
经典闭包和捕获变量问题。将循环更改为
for(int i=0;i<100;i++)
{
int j = i;
actions[i] = () => DoSomething(j);
}
有关更多信息:经典闭包和捕获变量问题。将循环更改为
for(int i=0;i<100;i++)
{
int j = i;
actions[i] = () => DoSomething(j);
}
有关更多信息: