问题描述
这个显然不是看起来不是最佳实践.有人可以解释为什么这不是最佳实践或它是如何工作的吗?任何提供解释的书籍或文章将不胜感激.
This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated.
//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";
}
输出的值是第二个值Modified".编译器魔术的哪一部分使这项工作起作用?这就像跟踪堆上的值并稍后再次检索它一样简单吗?
The value that is output is the second value "Modified". What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later?
:给定一些评论,把原句改一下……
: Given some of the comments, changing the original sentence some...
推荐答案
currentValue 不再是局部变量:它是一个捕获的 变量.这编译为:
currentValue is no longer a local variable: it is a captured variable. This compiles to something like:
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";
}
Jon Skeet 在 C# in Depth 中对此有很好的描述,另外还有一个 (没有那么详细)讨论这里.
Jon Skeet has a really good write up of this in C# in Depth, and a separate (not as detailed) discussion here.
请注意,变量 currentValue 现在位于堆上,而不是堆栈上 - 这有很多含义,尤其是它现在可以被各种调用者使用.
Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers.
这与 java 不同:在 java 中,变量的 value 被捕获.在 C# 中,变量本身被捕获.
This is different to java: in java the value of a variable is captured. In C#, the variable itself is captured.
这篇关于带委托的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!