When a variable is closed twice, where is it stored?

I was reading with interesting this article called C# Closures Explained, which states:

You see, the C# compiler detects when a delegate forms a closure which is passed out of the current scope and it promotes the delegate, and the associated local variables into a compiler generated class. This way, it simply needs a bit of compiler trickery to pass around an instance of the compiler generated class, so each time we invoke the delegate we are actually calling the method on this class.

So essentially a closed variable is stored as a member variable of an anonymous class that also contains the delegate representing the lambda expression or other code that is closing over the variable.

If that is the case, what happens when a method contains two different lambda expressions and both of them reference the same local variable?

void Test(IList list)
{
    int i = 0;

    list.Any( a => { Console.WriteLine("Lambda one says: {0}", i++); return true;} )
        .Any( a => { Console.WriteLine("Lambda two says: {0}", i++); return true;} );

}

I'm pretty sure I know the behavior here. My question is, where exactly is i stored?


There is only one closure class for that method, rather than one per anonymous method. That one class will have two instance methods and a field. The field will store the value of i , and the two methods will each correspond to your two anonymous methods.

链接地址: http://www.djcxy.com/p/51554.html

上一篇: lambda表达式与静态方法

下一篇: 当一个变量关闭两次时,它存储在哪里?