关闭中的Foreach变量

时间:2014-10-21 12:46:35

标签: c# variables foreach closures

使用.net 4.0,为什么以下代码打印出“一,二,三,四,五”而不是每次都打印出“五”?

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

据我所知,使用旧版本的.net,我应该遇到问题here(在闭包中使用foreach变量),但在这种情况下,代码似乎有效。

1 个答案:

答案 0 :(得分:2)

.Net 4.0在这里无关紧要。唯一的问题是c#编译器。从C#5.0开始,行为发生了变化。我认为你正在使用C#5.0编译器。

这意味着即使在.Net 2.0中,如果您使用Visual Studio 2012(假设默认C#编译器版本为5.0),此代码也可以使用

如果您正在使用Visual Studio 2012或更新版本,则默认使用C#5.0编译器,因此您不会看到该错误。