odd lambda behavior

前端 未结 3 1542
感动是毒
感动是毒 2021-02-20 08:36

I stumbled across this article and found it very interesting, so I ran some tests on my own:

Test One:

List actions = new          


        
相关标签:
3条回答
  • 2021-02-20 08:52

    This is because of variable capturing in C# that can be a little tricky

    In a nutshell, Each loop of the for loop is referring to the same variable i so the compiler uses the same lambda expression for all loops.

    If it is any consolation, This oddity is worse in javascript as javascript only has function scopes for variables so even your second solution won't do what you expect it to.

    This is also a very good explanation

    0 讨论(0)
  • 2021-02-20 08:54

    @Eric Lippert has explained this in great detail in his two-parts article:

    • Closing over the loop variable considered harmful
    • Closing over the loop variable, part two

    It is a must-read article, as it explains the behavior in depth and at implementation-level.

    0 讨论(0)
  • 2021-02-20 09:16

    Yes.

    In Test One the var i is captured in the loop, but i refers to a variable that is effectively declared once outside the loop, so all of the captured lambdas refer to the one variable. By the time you call the actions the value of i is 5 so all of the output is five.

    In Test Two the var j is captured in the loop, but in this case j is declared each time inside the loop, so all of the captured lambdas refer to the distinct variables. So calling the lambdas outputs the distinct values.

    0 讨论(0)
提交回复
热议问题