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

后端 未结 3 1273
醉酒成梦
醉酒成梦 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.

    0 讨论(0)
  • Have you tried:

    foreach (var action in m_Holder)
    {
        var a = action;
        temp.Add(p => a(p));
    }
    
    0 讨论(0)
  • 2020-12-11 13:00

    This is the infamous "closing over the loop variable" gotcha.

    • Closing over the loop variable considered harmful (and part two)
    0 讨论(0)
提交回复
热议问题