Hug*_*are 23 c# heap delegates closures
这显然不是看起来像它不会是一个最佳实践.有人可以解释为什么它不是最佳实践或如何工作?任何提供解释的书籍或文章将不胜感激.
//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)
输出的值是第二个值"已修改".编译器魔术的哪个部分使这个工作?这跟跟踪堆上的值并稍后再次检索它一样简单吗?
[编辑]:鉴于一些评论,改变原来的一些句子......
Mar*_*ell 29
currentValue不再是局部变量:它是一个捕获的变量.这编译成如下:
class Foo {
public string currentValue; // yes, it is a field
public void SomeMethod(object sender, EventArgs e) {
Response.Write(currentValue);
}
}
...
public Page_Index() {
Foo foo = new Foo();
foo.currentValue = "This is the FIRST value";
this.Load += foo.SomeMethod;
foo.currentValue = "This is the MODIFIED value";
}
Run Code Online (Sandbox Code Playgroud)
乔恩斯基特拥有的这一个很好的写了C#的深度,和一个独立的(而不是详细)讨论在这里.
请注意,变量currentValue现在位于堆上,而不是堆栈 - 这有很多含义,尤其是它现在可以被各种调用者使用.
这与java不同:在java 中捕获变量的值.在C#中,捕获变量本身.