In -depth discussing the problem of capturing variables in the C# cycle
In C#, developers encounter an interesting problem when using capture variables in cycle iteration. Consider the following code fragment:
Although the expected output is 0, 2, 4, 6, and 8, the code unexpectedly output five 10. The reason for this behavior is the captured variables
<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) { Console.WriteLine(act.Invoke()); }</code>
variable
Solve the problem of capture variables variable
In order to overcome this limit and allow each operation to have its own capture variables, C# provides a simple solution:
By creating a copy of thein the cycle, each operation captures its own sole examples, so as to ensure that
changes outside the lambda expression will not affect the capture value.<code class="language-csharp">while (variable < 5) { int copy = variable; actions.Add(() => Console.WriteLine(copy * 2)); ++variable; }</code>
Other common situations variable
variable
and iteration:
In these two cases, the local copy of the variable is required to capture the current cycle iteration. for
foreach
Conclusion
<code class="language-csharp">// For loop for (int i = 0; i < 5; i++) { // ... similar issue ... } // Foreach loop // ... similar issue ...</code>
Understanding the behavior of capturing variables in the C# cycle is essential to avoid accidents. The solution discussed in this article ensures that each operation has its own independent capture variables, thereby achieving predictable and expected behaviors.
The above is the detailed content of Why Do C# Loops with Captured Variables Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!