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

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

Suppose we have the following code:

void AFunction()
{

   foreach(AClass i in AClassCollection)
   {
      listOfLamb         


        
5条回答
  •  天命终不由人
    2020-12-06 18:12

    does the lambda function somehow store a 'reference' to the variable or something?

    Close. The lambda function captures the variable itself. There is no need to store a reference to a variable, and in fact, in .NET it is impossible to permanently store a reference to a variable. You just capture the entire variable. You never capture the value of the variable.

    Remember, a variable is a storage location. The name "i" refers to a particular storage location, and in your case, it always refers to the same storage location.

    Is there anyway around this problem?

    Yes. Create a new variable every time through the loop. The closure then captures a different variable every time.

    This is one of the most frequently reported problems with C#. We're considering changing the semantics of the loop variable declaration so that a new variable is created every time through the loop.

    For more details on this issue see my articles on the subject:

    http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/

提交回复
热议问题