To illustrate my confusion, see the following example:
int a = 0;
Action act = () => ++a;
act();
Console.WriteLine(a);
I have difficulty figuring out how modification to the captured variable within the lambda could possibly affect the local variable a
. First of all, the implicitly generated lambda function object could not store a reference to the local variable a
. Otherwise, if act
is returned and invoked later, the referenced local variable a
would already be vanished. A solution to this problem would be copy-by-value, either by copying the int
value directly or through boxing, so that the function object would have its own copy the local variable a
. But this doesn't explain the example just given. So, what is the underlying mechanism? Would it be that the seemingly local variable a
is actually no longer a local variable, but translated by the compiler to be a reference to an int
field within the generated lambda function object?
The point here is closure . After compilation a
is not a local variable anymore - it's a field of auto-generated class, both in function scope and in lambda.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.