Home >Backend Development >C++ >Why Does My C# Loop Capture the Wrong Variable Value?
Cover variable in the cycle: a strange problem
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.
<code class="language-csharp">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(); }</code>
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.
<code class="language-csharp">while (variable < 5) { int copy = variable; actions.Add(() => Console.WriteLine(copy * 2)); ++variable; }</code>Precautions
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!