The reason for discovering a bug in the program is that the declaration variable (that is, the common variable I) is captured by delegate in the for loop ), this happens when you capture the Declaration variable of the for loop, but call the delegate only after the declaration variable has changed. You expect the value of the variable to be captured, but the result is the final value of the variable, even if the variable type is a value type. Let's look at this Code:
VaR list = new action [5];
For (INT I = 0; I <5; I ++)
{
List [I] = new action () => console. writeline (I ));
}
Foreach (var a in List)
A ();
Obviously, I expect each action to capture the current value, but the output will be:
5
5
5
5
5
In for, the life variable is actually a local global variable, just like this:
Int I = 0;
For (; I <5; I ++)
{/*...*/}
The solution is to save the current value by declaring a local temporary variable without the Declaration variable of this for loop:
For (; I <5; I ++)
{
VaR local = I;
List [I] = new action () => console. writeline (local ));
}
In this way, five will not be output.
Of course, this problem will not occur if list. foreach is used. Code:
VaR list = new action [5];
Enumerable. Range (0, 5). tolist (). foreach (I =>
{
List [I] = new action () => console. writeline (I ));
});
Foreach (var a in List)
A ();
Output:
0
1
2
3
4