问题描述
这个似乎不是最佳做法。有人可以解释为什么这不是一个最佳实践或者这是如何工作的?任何提供解释的书籍或文章将不胜感激。
This 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";
}
输出的值是第二个值 修改。编译器魔术的哪一部分使这项工作?这是简单的跟踪堆上的值并再次检索吗?
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在和一个单独的(不详细的)讨论。
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中值捕获一个变量。在C#中,捕获变量本身。
This is different to java: in java the value of a variable is captured. In C#, the variable itself is captured.
这篇关于带代表的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!