Different behaviors with a for loop and a foreach loop with closures

后端 未结 3 1286
醉酒成梦
醉酒成梦 2020-12-11 12:31

I can\'t explain an issue I\'ve run across. Basically I get a different answer if I use lambda syntax in a foreach loop than if I use it in a for loop. In the code below I r

3条回答
  •  醉酒成梦
    2020-12-11 12:42

    This is the classic issue of a captured closure with a scope that isn't what you expect. In the foreach, the action has outer scope, so the execution captures the last value of the loop. In the for case, you create the action in inner scope, so the closure is over the local value at each iteration.

提交回复
热议问题