C#闭包,为什么是loopvariable参照抓获? [英] C# Closures, why is the loopvariable captured by reference?
问题描述
在这个例子中,我试图按值传递,但引用,而不是通过。
In this example, I'm attempting to pass by value, but the reference is passed instead.
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(() => new PhoneJobTest(i);
t.Start();
}
这是可以纠正的,像这样:
This can be remedied like so:
for (int i = 0; i < 10; i++)
{
int jobNum = i;
Thread t = new Thread(() => new PhoneJobTest(jobNum);
t.Start();
}
什么是怎么回事?为什么原来的例子将引用传递?
What's is going on here? Why does the original example pass the reference?
推荐答案
好吧,这是多么的C#工程。在你的语句中的拉姆达前pression构建了一个封闭的词汇,它存储的单一参考 I
的持续循环已经结束后还是一样。
Well, that's just how C# works. The lambda expression in your statement constructs a lexical closure, which stores a single reference to i
that persists even after the loop has concluded.
要解决它,你可以做到这一点,你做的东西。
To remedy it, you can do just the thing that you did.
随意阅读更多关于这个具体问题各地的网络;我的选择是<一个href=\"http://blogs.msdn.com/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx\">Eric利珀特的讨论在这里。
Feel free to read more on this particular issue all around the Web; my choice would be Eric Lippert's discussion here.
这篇关于C#闭包,为什么是loopvariable参照抓获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!