带委托的局部变量

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.

这篇关于带委托的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Is there a runtime benefit to using const local variables?(使用 const 局部变量有运行时的好处吗?)
How to avoid #39;Unassigned Local Variable#39; defined inside a try-catch block(如何避免在try-Catch块中定义未赋值的局部变量)
When does a local variable inside a function *actually* gets allocated(函数内的局部变量何时*实际*被分配)
How to remove compiler error with struct: quot;Use of unassigned local variablequot;(如何使用 struct 删除编译器错误:“使用未分配的局部变量)
Strange behavior with actions, local variables and garbage collection in MVVM light Messenger(MVVM light Messenger 中的动作、局部变量和垃圾收集的奇怪行为)
Why does this (null || !TryParse) conditional result in quot;use of unassigned local variablequot;?(为什么这个 (null || !TryParse) 条件会导致“使用未分配的局部变量?)