C# lambda, local variable value not taken when you think?

后端 未结 5 794
清歌不尽
清歌不尽 2020-12-06 17:37

Suppose we have the following code:

void AFunction()
{

   foreach(AClass i in AClassCollection)
   {
      listOfLamb         


        
5条回答
  •  甜味超标
    2020-12-06 18:11

    Yes, the lambda stores a reference to the variable (conceptually speaking, anyway).

    A very simple workaround is this:

     foreach(AClass i in AClassCollection)
       {
          AClass j = i;
          listOfLambdaFunctions.AddLast(  () =>  {  PrintLine(j.name); }  );
       }
    

    In every iteration of the foreach loop, a new j gets created, which the lambda captures. i on the other hand, is the same variable throughout, but gets updated with every iteration (so all the lambdas end up seeing the last value)

    And I agree that this is a bit surprising. :)

提交回复
热议问题