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了。

相关文章:

  • 2021-11-05
  • 2021-10-15
  • 2021-09-25
  • 2022-02-21
  • 2022-02-06
  • 2022-12-23
  • 2022-12-23
  • 2021-06-05
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-11
  • 2022-02-19
  • 2022-12-23
  • 2021-06-05
相关资源
相似解决方案