Where does anonymous function body variables saved ?

不羁岁月 提交于 2019-12-24 13:26:03

问题


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

thanks

    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;
    }

回答1:


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.

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.




回答2:


They're saved in a generated closure class in the delegates' Target fields.

For more information, see my blog post.



来源:https://stackoverflow.com/questions/10658658/where-does-anonymous-function-body-variables-saved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!