匿名代理生命周期范围 [英] Anonymous Delegate lifetime scope

查看:76
本文介绍了匿名代理生命周期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在一个使用该函数的局部变量的函数中定义了一个匿名委托,但是可以在该函数外部调用该匿名方法(例如将其添加到列表中),那么该局部变量又如何呢?匿名委托使用的变量?

If one defines an anonymous delegate, say, inside a function that uses a local variable of that function but the anonymous method can be called outside the function(say it is added to a list) then how is the local variable used by the anonymous delegate?

 

一个测试表明该变量确实具有正确的值,我认为这是因为未经GC处理.它还表明变量具有最后一个值(在函数调用结束之前,而不是之前(通常是您对它的看法)).

A test shows that the variable does have the correct value which I assume is because it is not GC'ed. It also showed that the variable has the last value(right before the function call ended rather than the before(which is generally how you think about it)).

 

这似乎很容易出错,但我想是可以接受的.

This seems highly error prone but I guess is acceptable.

 

但是该函数的堆栈本身是如何定义的?该功能也不是GC的吗?

But how is the stack itself for the function defined? Is the function not GC'ed either?

在匿名函数的定义中使用非局部变量时,似乎必须格外小心.据我所知这样做是没有用的(因为它超出了函数的范围)并且抛出了错误警告显示?

It seems one has to be extremely careful when using non-local variables inside the definition of an anonymous function. As far as I can tell it is useless to do so(Since it is outside the scope of the function) and an error warning show be thrown?

推荐答案

匿名函数是语法糖,编译器通常会将其转换转换为适当的命名函数.在您提到的情况下,编译器通常会更进一步,并使用您的函数和一个成员变量创建一个类来存储 委托对象的生命周期所需的数据.例如,如果您调查从以下简单程序生成的代码的IL.

Anonymous functions are syntactic sugar, the compiler generally turns them into proper named functions.  In the case you mention, the compiler will generally go a step further and create a class with your function and a member variable to store the data it needs for the lifespan of the delegate object.  For instance, if you investigate the IL for the code generated from the following simple program.


class Program
{
  static void Main(string[] args)
  {
    Func1();
    Func2();
    Func2();
  }

  delegate void SimpleDelegate();
  static SimpleDelegate CallMeLater;

  static void Func1()
  {
    int q = 42;
    CallMeLater = new SimpleDelegate(delegate()
    {
      Console.Write(q.ToString() + " - ");
      q += 1;
      Console.WriteLine(q.ToString());
    });
  }

  static void Func2()
  {
    CallMeLater();
  }
}


这篇关于匿名代理生命周期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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