Local variables with Delegates(带委托的局部变量)
问题描述
这个显然不是看起来不是最佳实践.有人可以解释为什么这不是最佳实践或它是如何工作的吗?任何提供解释的书籍或文章将不胜感激.
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.
这篇关于带委托的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带委托的局部变量


- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01