C #: capture external variables in anonymous methods,
First, introduce the topic with a piece of code. If you can directly output the code, it means this article is not suitable for you. (The code is introduced in the third edition of "understanding C)
class Program { private delegate void TestDelegate(); static void Main(string[] args) { TestDelegate[] delegates = new TestDelegate[2]; int outside = 0; for(int i = 0; i < 2; i++) { int inside = 0; delegates[i] = delegate { Console.WriteLine("({0},{1})", outside, inside); outside++; inside++; }; } delegates[0](); delegates[0](); delegates[0](); delegates[1](); delegates[1](); Console.ReadKey(); } }
The answer is at the bottom of this article.
Two definitions are introduced first:
1. external variables: local variables or parameters that include anonymous methods in the scope.
2. Captured external variables: external variables used in anonymous methods.
The definition is a bit abstract. For the above Code, both inside and outside are external variables of anonymous methods, while inside and outside are also external variables captured by anonymous methods, because these two variables are referenced in the anonymous method body.
What is captured by the anonymous method is the variable itself, not the value of the variable. For the above Code, when outside ++ and inside ++ are executed, the operations are actually external inside and outside variables.
So far, we can see that the outside change is from 0 to 4.
The output of the program should look like this: (The X code is unknown)
(0, X)
(1, X)
(2, X)
(3, X)
(4, X)
In fact, what we do in the for loop body is to instantiate two TestDelegate delegate objects: delegate [0] and delegate [1].
Loop execution will actually instantiate two variables named inside.
There is no association between these two variables, just the same name.
These two variables are used as external capture variables for delegate [0] and delegate [1] respectively. That is, when delegate [0] and delegate [1] operate inside, they do not affect each other.
The answer is as follows:
)Answer