具有代理的局部变量 [英] Local variables with Delegates

查看:198
本文介绍了具有代理的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个显然不是似乎不是最佳实践。有人可以解释为什么它不会是一个最佳实践或这是如何工作的?

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";

}

输出的值是第二个值 修改。编译器的什么部分魔法使这项工作?这是简单的跟踪堆上的值,并在稍后再次检索它吗?

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中的捕获变量。在C#中,会捕获变量本身

This is different to java: in java the value of a variable is captured. In C#, the variable itself is captured.

这篇关于具有代理的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆