我一直在学习C#,并且我正试图理解lambda。在下面的这个例子中,它打印出10次10次。如何告诉lambda函数在C#中捕获副本而不是参考?
class Program
{
delegate void Action();
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 10; ++i)
actions.Add(()=>Console.WriteLine(i));
foreach (Action a in actions)
a();
}
}
显然,拉姆达后面生成的类被存储的引用或指针int i
可变的,并且每当分配一个新的值,以相同的附图的循环迭代。有没有办法迫使LAMDA抢副本,而不是一样的C++ 0x语法
[&](){ ... } // Capture by reference
与
[=](){ ... } // Capture copies
您可能想要阅读[本文](http://csharpindepth.com/Articles/Chapter5/Closures.aspx),由我们自己的Jon Skeet编写。 – 2009-01-16 20:12:41
[C#捕获变量循环]可能的重复(http://stackoverflow.com/questions/271440/c-sharp-captured-variable-in-loop) – nawfal 2013-11-02 06:35:41