Lambda capture problem with iterators?

后端 未结 4 383
自闭症患者
自闭症患者 2020-12-20 04:00

Apologies if this question has been asked already, but suppose we have this code (I\'ve run it with Mono 2.10.2 and compiled with gmcs 2.10.2.0):



        
4条回答
  •  时光说笑
    2020-12-20 04:37

    The following happens in loop 1 and 3:

    The current value is assigned to the variable str. It is always the same variable, just with a different value in each iteration. This variable is captured by the lambda. As the lambda is executed after the loop finishes, it has the value of the last element in your array.

    The following happens in loop 2:

    The current value is assigned to a new variable localStr. It is always a new variable that gets the value assigned. This new variable is captured by the lambda. Because the next iteration of the loop creates a new variable, the value of the captured variable is not changed and because of that it outputs "foo".

提交回复
热议问题