带代表的局部变量 [英] Local variables with Delegates

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

问题描述

这个显然不是似乎不是最佳做法。有人可以解释为什么这不是一个最佳实践或者这是如何工作的?任何提供解释的书籍或文章将不胜感激。

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#和一个单独的(不详细的)讨论这里

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天全站免登陆