Is there a reason for C#'s reuse of the variable in a foreach?

前端 未结 4 835
梦如初夏
梦如初夏 2020-11-21 22:27

When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example:

foreach (var s          


        
4条回答
  •  悲哀的现实
    2020-11-21 23:13

    What you are asking is thoroughly covered by Eric Lippert in his blog post Closing over the loop variable considered harmful and its sequel.

    For me, the most convincing argument is that having new variable in each iteration would be inconsistent with for(;;) style loop. Would you expect to have a new int i in each iteration of for (int i = 0; i < 10; i++)?

    The most common problem with this behavior is making a closure over iteration variable and it has an easy workaround:

    foreach (var s in strings)
    {
        var s_for_closure = s;
        query = query.Where(i => i.Prop == s_for_closure); // access to modified closure
    

    My blog post about this issue: Closure over foreach variable in C#.

提交回复
热议问题