任何人都可以解释下面的代码中发生了什么?为什么没有印刷品?
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);
}
Run Code Online (Sandbox Code Playgroud)
Ese*_*ser 10
经典闭包和捕获变量问题.改变你的循环
for(int i=0;i<100;i++)
{
int j = i;
actions[i] = () => DoSomething(j);
}
Run Code Online (Sandbox Code Playgroud)
欲了解更多信息:http://csharpindepth.com/articles/chapter5/closures.aspx
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |