C# 5.0 Capture closures in loops: Differences between For loops and Foreach loops
question:
In C# 5.0, the capture closure in the foreach loop can be captured correctly, but why is the capture closure in the for loop still having problems?
answer:
Logically speaking, the behavior of closures in a for loop is reasonable. After decomposing the for loop into its components (initializer, condition, iterator, and body), the initializer executes only once. Therefore, it is logical to have only one "variable instantiation".
In addition, in the for loop, the initial value of the variable for each iteration is not predetermined. Consider the following example:
for (int i = 0, j = 10; i Console.WriteLine(i, j);
action();
}
In this loop, the value of j may change during the loop. What is the expected behavior in this case?
In contrast, the foreach loop seems to declare a new variable for each iteration, and that variable is read-only. Therefore, it is reasonable to think of a foreach loop as declaring a separate read-only variable in each iteration whose value is taken from the iterator. This explains why closures can be captured correctly in the foreach loop.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3