[英]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.