C#
Reuse of cycle variables: an unnecessary trap foreach
When using lambda expression or anonymous method in C#, a modified closure access may appear.
foreach
The compiler usually declares the cycle variable outside the cycle body, as shown in the modified closure example:
This is different from the expectations of declared variables in the cycle:
string s; while (enumerator.MoveNext()) { s = enumerator.Current; ... }
The external variable statement has exacerbated the modified closure access problem because it creates a longer scope for variables. The variables declared in the <环> cycle cannot be accessed outside the cycle.
while (enumerator.MoveNext()) { string s; s = enumerator.Current; ... }
The compiler decides to reuse the circular variable before the introduction of Lambda expression and anonymous method. Therefore, there was no potential trap that the variable reuse was fully considered at the time. foreach
Although this repair is a popular improvement, when using the old version of the old version or not supporting this repair, it still needs to pay attention to this problem.
The above is the detailed content of Why Does C#'s `foreach` Loop Variable Reuse Cause Problems with Closures?. For more information, please follow other related articles on the PHP Chinese website!