简体   繁体   English

闭包中的Foreach变量

[英]Foreach variable in closure

Using .net 4.0, why does the following code print out 'one, two, three, four, five' rather than just printing out 'five' every time? 使用.net 4.0,为什么下面的代码为什么每次打印“ 1、2、3、4、5”而不是每次打印“ 5”?

public void Go()
{
    List<Action> printActions = new List<Action>();
    String[] strings = new[] {"one", "two", "three", "four", "five"};

    foreach (String s in strings)
        printActions.Add(() => Console.WriteLine(s));

    foreach (Action printAction in printActions)
        printAction();
}

As far as I can tell, using older versions of .net, i should be running into the problem addressed here (using foreach variable in a closure), but in this case, the code appears to work. 据我所知,使用旧版本的.net,我应该遇到这里解决的问题(在闭包中使用foreach变量),但是在这种情况下,代码似乎可以正常工作。

.Net 4.0 is irrelevant here. .Net 4.0与此处无关。 Only thing is the c# compiler. 唯一的是C#编译器。 Starting from C# 5.0 behavior is changed. 从C#5.0开始,行为已更改。 I presume you're using C# 5.0 compiler. 我想您正在使用C#5.0编译器。

This means that even in .Net 2.0 this code will work if you're using Visual studio 2012 (given that default C# compiler version is 5.0) 这意味着,即使您使用的是Visual Studio 2012,即使在.Net 2.0中,此代码也可以使用(假定默认的C#编译器版本为5.0)

If you're using Visual studio 2012 or newer version by default C#5.0 compiler will be used and hence you don't see the bug. 如果您使用的是Visual Studio 2012或更高版本,则默认情况下将使用C#5.0编译器,因此看不到该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM