Is “Access to modified closure” resolved by comprehension syntax?

前端 未结 2 1817
广开言路
广开言路 2020-12-10 04:57

ReSharper 6.0 gives me the \"Access to modified closure\" warning for the dr identifier in the first code snippet.



        
2条回答
  •  猫巷女王i
    2020-12-10 05:52

    First off, you are correct to be concerned about the first version. Each delegate created by that lambda is closed over the same variable and therefore as that variable changes, the meaning of the query changes.

    Second, FYI we are highly likely to fix this in the next version of C#; this is a major pain point for developers.

    (UPDATE: This answer was written in 2011. We did in fact take the fix described below in C# 5.)

    In the next version each time you run through the "foreach" loop we will generate a new loop variable rather than closing over the same variable every time. This is a "breaking" change but in the vast majority of cases the "break" will be fixing rather than causing bugs.

    The "for" loop will not be changed.

    See http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/ for details.

    Third, there is no problem with the query comprehension version because there is no closed-over variable that is being modified. The query comprehension form is the same as if you'd said:

    return dt.Rows.Select(dr=>GetStringFuncOutput(dr.ToString));
    

    The lambda is not closed over any outer variable, so there is no variable to be modified accidentally.

提交回复
热议问题