How does a lambda in C# bind to the enumerator in a foreach?

后端 未结 5 1825
囚心锁ツ
囚心锁ツ 2020-12-09 18:27

I just came across the most unexpected behavior. I\'m sure there is a good reason it works this way. Can someone help explain this?

Consider this code:



        
5条回答
  •  青春惊慌失措
    2020-12-09 19:06

    Since the foreach construct is just syntactic sugar it is best to think of it in it's true form.

    int num;
    while (nums.MoveNext())
    {
        num = nums.Current;
        actions.Add(() => num);
    }
    

    The lambda will capture the num variable so when you execute the lambda the latest value of num will be used.

提交回复
热议问题