您的位置:首页 > 其它

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

2014-02-06 16:50 375 查看
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了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐