闭包一个容易忽视的小问题及解决方法

 

Action[] tmp = new Action[3];

for (int i = 0; i < tmp.Length; i++)
{
    tmp[i] = () => Console.WriteLine(i);
}

Array.ForEach(tmp, m => m());

Console.Read();


猜猜打印结果会是啥,012 ?

结果吓一跳

自己仔细想想差不多明白了,闭包是嵌套的,外面一级变量i在作用域里,所以他会返回i最后的值。

修改了下

Action[] tmp = new Action[3];

for (int i = 0; i < tmp.Length; i++)
{
    int j = i;
    tmp[i] = () => Console.WriteLine(j);
}

Array.ForEach(tmp, m => m());

Console.Read();

 

ok了,正确输出012了。

posted @ 2014-02-06 16:50  HONT  阅读(1208)  评论(0编辑  收藏  举报