[英]Running same program on VS2012 and VS2010 exhibits different behavior
I have .net 4.5 installed on my box and I understand that below behavior is related to difference in the way foreach captures closure between .net 3.5 and 4. 我在我的盒子上安装了.net 4.5,我知道以下行为与foreach捕获.net 3.5和4之间的关闭方式的不同有关。
I'd like to better understand why running the same code in both VS 2012 and then with VS2010 shows different output when I compiling using .net Framework 4 in both cases, is it that VS 2012 runs csc with some special flag that cause it to capture closure? 我想更好地理解为什么在VS 2012中运行相同的代码然后在VS2010中显示不同的输出,当我在两种情况下使用.net Framework 4进行编译时,是否VS 2012运行csc并带有一些特殊标志,导致它捕获闭合?
var words = new[] { "foo", "bar", "baz", "beer" };
var actions = new List<Action>();
foreach (string word in words)
{
actions.Add(() => Console.WriteLine(word));
}
actions.ForEach(e => e());
Output: With VS2010 and .net 4, above program yields "beer" 4 times 输出:使用VS2010和.net 4,上述程序产生“啤酒”4次
With VS2012 and .net 4: 使用VS2012和.net 4:
foo bar baz beer foo bar巴兹啤酒
The fix for this was not part of .Net 4, it was part of C# 5. Thus, it is the compiler you are using, rather than the framework version you are targeting, that affects the behavior of this code. 对此的修复不是.Net 4的一部分,它是C#5的一部分。因此,它是您正在使用的编译器,而不是您所针对的框架版本,它会影响此代码的行为。
This is discussed here , and officially declared here . 这将在这里讨论,并在此正式宣布。
It was a kine of bug , that Microsoft fix it in VS2012. 这是一个bug的发现,微软在VS2012中修复它。 i don't know, did Microsoft fix it in VS 2010 in Last SP?. 我不知道,微软是否在最后SP的VS 2010中修复了它? if you test it please inform us. 如果你测试它,请通知我们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.