odd lambda behavior

前端 未结 3 1570
感动是毒
感动是毒 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

提交回复
热议问题