匿名函数主体变量保存在哪里? [英] Where does anonymous function body variables saved ?

查看:183
本文介绍了匿名函数主体变量保存在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有效,但是为什么呢?当我在循环中调用匿名方法时,x和y会在哪里保存?

Below code is working but why ? Where does the x and y coming/saved when I invoke anonymous method in the loop.

谢谢

    static void Main(string[] args)
    {
        int x=1;
        int y=2;
        var dic = GetDic(x, y);

        for (int i = 0; i < 5;i++ )
        {
            System.Console.WriteLine(dic[i].Invoke().ToString());
        }

    }

    private static Dictionary<int, Func<int>> GetDic(int x, int y)
    {
        var dic = new Dictionary<int, Func<int>>()
        {
            {0,()=>{return y;}},
            {1,()=>{return x;}},
            {2,()=>{return x+y;}},
            {3,()=>{return x-y;}},
            {4,()=>{return y-x;}},
        };
        return dic;
    }


推荐答案

Lambda表达式被编译为单独的表达式方法。如果它们不使用周围代码中的局部变量,则将它们编译为同一类的方法。但是,当使用局部变量时(例如在这种情况下),编译器将在周围的类型中创建一个嵌套类,并将已编译的方法和与使用的局部变量匹配的字段放在此处。使用lambda表达式时,将创建该类的实例,并将值存储在实例字段中,以便lambda方法可以访问它们。

Lambda expressions are compiled into separate methods. If they don't use local variables from the surrounding code, they are compiled into methods of the same class. However, when local variables are used (like in this case), the compiler creates a nested class in the surrounding type and puts the compiled method and fields matching the used local variables there. When the lambda expression is used, an instance of that class is created and the values are stored in instance fields so the lambda method has access to them.

与仅使用参数和其他类型的静态成员的lambda表达式相比,在lambda表达式中使用周围方法的局部变量要昂贵得多。

This also implies that using local variables from the surrounding method in a lambda expression is slightly more expensive than a lambda expression that only uses its parameters and static members of other types.

这篇关于匿名函数主体变量保存在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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