这显然不是看起来像它不会是一个最佳实践.有人可以解释为什么它不是最佳实践或如何工作?任何提供解释的书籍或文章将不胜感激.
//The constructor
public Page_Index() {
//create a local value
string currentValue = "This is the FIRST value";
//use the local variable in a delegate that fires later
this.Load += delegate(object sender, EventArgs e) {
Response.Write(currentValue);
};
//change it again
currentValue = "This is the MODIFIED value";
}
Run Code Online (Sandbox Code Playgroud)
输出的值是第二个值"已修改".编译器魔术的哪个部分使这个工作?这跟跟踪堆上的值并稍后再次检索它一样简单吗?
[编辑]:鉴于一些评论,改变原来的一些句子......
这是一个基于Eric Lippert 撰写的文章"Closing over the loop variable related harm"的问题.
这是一个很好的阅读,Eric解释了为什么在这段代码之后所有的funcs将返回v中的最后一个值:
var funcs = new List<Func<int>>();
foreach (var v in values)
{
funcs.Add(() => v);
}
Run Code Online (Sandbox Code Playgroud)
正确的版本看起来像:
foreach (var v in values)
{
int v2 = v;
funcs.Add(() => v2);
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是那些捕获的'v2'变量存储的方式和位置.在我对堆栈的理解中,所有这些v2变量都会占用同一块内存.
我的第一个想法是拳击,每个func成员保持对盒装v2的引用.但这并不能解释第一种情况.