Вопрос

are there any differences in the references that are produced in code generated for anonymous methods by a .NET 2.0 or 4.0 compiler and code generated for an equivalent lambda by a .NET 4.0 compiler? and in particular for the this pointer: I know both anonymous methods and lambdas are a C# compiler feature and the compiler actually generates a nested class with a delegate and all the references required for outer variables, but this article on the implementation of anonymous methods states a reference is kept to the pointer and I cannot find any source describing anything similar for lambdas.. or am I not finding anything because the implementation for compiling anonymous methods maps 1 on 1 to that of lambdas?

here's a bit of code to demonstrate anonymous methods and lambdas:

    class AnonymousMethodMethodScope
    {
        private Func<bool> d;
        public Func<int, bool> d2;
        int j = 0;

        public void Test(int i)
        {
            d = new Func<bool>(delegate { j = 10; return j > i; });

            // what references does this anonymous method keep?
            d2 = new Func<int, bool>(delegate(int x) { return x == j; });

            Console.WriteLine("j = " + j + " result = " + d());
        }
    }

    class LambdaMethodScope
    {
        private Func<bool> d;
        public Func<int, bool> d2;

        public void Test(int i)
        {
            int j = 0;

            d = () => { j = 10; return j > i; };

            // what references does this lambda keep?
            d2 = x => x == j;

            Console.WriteLine("j = " + j + " result = " + d());
        }
    }
Это было полезно?

Решение

Yes, lambda expressions will do (and have to do) the same thing as anonymous methods when it comes to capturing variables. (I'm assuming you're talking about lambda expressions which are converted into delegates; if they're converted into expression trees they may be a bit different - I'm not sure.)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top