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

后端 未结 5 1819
囚心锁ツ
囚心锁ツ 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:14

    This is because of two following things:
    1) delegates save context (scope) of outside variables
    2) first foreach cycle will compile in only one "num" variable declared.
    3) lazy evaluation

    Each delegated added in the first cycle will save the same num variable saved to the scope. Because of lazy evaluation you will run the delegates after the first cycle is finished, so num veraible, saved to the delegates' scope equals 4.

提交回复
热议问题