c# – 为什么在Array.ForEach中输出333不是0112?

参见英文答案 >
Is there a reason for C#’s reuse of the variable in a foreach?                                    5个

为什么下面的代码输出333不是012?

我认为代码是如此简单,我检查和检查,仔细检查,三重检查,还不能得到答案.任何人都可以帮助我吗?

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();

最佳答案 您应该将代码更改为:

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();

原因是关闭是巢

更多详细信息请查看以下链接:
Is there a reason for C#’s reuse of the variable in a foreach?
http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/

点赞