简体   繁体   中英

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?

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 4.0 is irrelevant here. Only thing is the c# compiler. Starting from C# 5.0 behavior is changed. I presume you're using C# 5.0 compiler.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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