Scope of variables in a delegate

前端 未结 6 1479
醉酒成梦
醉酒成梦 2021-01-05 04:53

I found the following rather strange. Then again, I have mostly used closures in dynamic languages which shouldn\'t be suspectable to the same \"bug\". The following makes t

6条回答
  •  不思量自难忘°
    2021-01-05 05:33

    If I remember correctly, the compiler creates a class member of the outside variables referenced in the anonymous method, in order to make this work.

    Here is a workaround:

    class Program
        {
            void Main()
            {
                VoidFunction t = RealFunction;
                int i = 1;
            }
            delegate void VoidFunction();
            void RealFunction() { int i = 0; }
        } 
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题