内部匿名方法中变量的范围 [英] The scope of variable in inner anonymous method

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

问题描述

查看代码

public class Test
{
    public static void Main()
    {
        Test t = new Test();
        var AnonymousMethod = t.OuterMethod();
        AnonymousMethod("passedValue");
    }
     public delegate void SampleDelegate(string InputText);

     public SampleDelegate OuterMethod()
    {
        string outerValue="outerValue";
        return (x => {
            Console.WriteLine(x);
            Console.WriteLine(outerValue);
        });

    }
}

OutPut

Success  time: 0.02 memory: 33816 signal:0
passedValue
outerValue

链接到示例

通常,变量 outerValue 的范围将在调用 t.OuterMethod()之后结束。但是在使用匿名类型的情况下,控制台打印输出清楚( Console.WriteLine(outerValue)),这意味着变量的作用域没有结束。实际上编译器做什么来确定其范围?它会将 Main 方法的范围分配给匿名方法中使用的变量吗?我知道如何使用,但不知道它是如何工作的。请指导我?

Normally the scope of variable outerValue would end after calling t.OuterMethod(). But in the case of using anonymous type, Console printed the output clearly (Console.WriteLine(outerValue)) which means the scope of variable didn't end. What do actually the compiler do to determine its scope? Will it assign the scope of Main method to the variables used inside the anonymous method? I know how to use but don't know how it works. Please guide me?

编辑


附加到事件的匿名方法。该事件可能是
以后执行很多。然后变量将在内存中。仪式?如果
分配了很多事件,很多内存!这是一个坏事我想。
我有什么错误吗?

Suppose the anonymous method attached to an event. The event might be executing a lot later. Then the variable would be in memory. rite? If a lot of events assigned, a lot of memory!. Its a bad thing I suppose. Did I make any mistake?


推荐答案

变量的范围

变量的生存期被有效地扩展:lambda表达式

The "lifetime" of the variable is effectively extended: the lambda expression captures the variable. The compiler will have generated a private nested class for you, with that variable in - both the method and the delegate refer to the same instance of this nested class, and that instance won't be eligible for garbage collection until the method no longer refers to it and the delegate instance is eligible for garbage collection.

这篇关于内部匿名方法中变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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