Questions tagged «captured-variable»

9
在C#中的循环中捕获的变量
我遇到了一个有关C#的有趣问题。我有下面的代码。 List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 5) { actions.Add(() => variable * 2); ++ variable; } foreach (var act in actions) { Console.WriteLine(act.Invoke()); } 我希望它输出0、2、4、6、8。但是,实际上它输出5个10s。 看来这是由于所有操作都引用了一个捕获的变量。结果,当它们被调用时,它们都具有相同的输出。 有没有办法解决这个限制,使每个动作实例都有自己的捕获变量?
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.