匿名函数体变量保存在哪里

匿名函数体变量保存在哪里

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

问题描述

下面的代码有效,但为什么?当我在循环中调用匿名方法时,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.

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

09-05 23:21