When using the C#cycle, you may encounter a special problem to capture variables. Let's consider the following scenes:
In contrast to expected, this code prints five "10" instead of the expected sequence 0, 2, 4, 6, 8.
List<Action> actions = new List<Action>(); int variable = 0; while (variable < 5) { actions.Add(() => Console.WriteLine(variable * 2)); ++variable; } foreach (var act in actions) { act.Invoke(); }
<:> Question: The capture variable in the cycle
All Lambda functions created in the cycle capture the same variable . Therefore, when these functions are called outside, they all quote the final value of
.
variable
<决> Solution: Copy rescue variable
In order to solve this problem, you need to create a copy of the variable in the cycle, and then capture it in each lambda function:
By creating a copy, each closure created in the cycle will capture its ownunique value, thereby generating expected output.
while (variable < 5) { int copy = variable; actions.Add(() => Console.WriteLine(copy * 2)); ++variable; }
variable
The above is the detailed content of Why Does My C# Loop Capture the Wrong Variable Value?. For more information, please follow other related articles on the PHP Chinese website!