繁体   English   中英

闭包中的Foreach变量

[英]Foreach variable in closure

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

据我所知,使用旧版本的.net,我应该遇到这里解决的问题(在闭包中使用foreach变量),但是在这种情况下,代码似乎可以正常工作。

.Net 4.0与此处无关。 唯一的是C#编译器。 从C#5.0开始,行为已更改。 我想您正在使用C#5.0编译器。

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

如果您使用的是Visual Studio 2012或更高版本,则默认情况下将使用C#5.0编译器,因此看不到该错误。

暂无
暂无

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

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