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

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

Suppose we have the following code:

void AFunction()
{

   foreach(AClass i in AClassCollection)
   {
      listOfLamb         


        
5条回答
  •  一个人的身影
    2020-12-06 18:20

    what is going on? does the lambda function somehow store a 'reference' to the variable or something?

    Yes exactly that; c# captured variables are to the variable, not the value of the variable. You can usually get around this by introducing a temp variable and binding to that:

    string astr = "a string";
    var tmp = astr;
    AFunc fnc = () => { System.Diagnostics.Debug.WriteLine(tmp); };
    

    especially in foreach where this is notorious.

提交回复
热议问题