In closure, what triggers a new instance of the captured variable?

前端 未结 2 1688
鱼传尺愫
鱼传尺愫 2021-01-13 09:53

I\'m reading Jon Skeet\'s C# in Depth.

On page 156 he has an example, Listing 5.13 \"Capturing multiple variable instantiations with multiple delegates\".

         


        
2条回答
  •  误落风尘
    2021-01-13 10:47

    As far as I understood closures. It is the anonymous delegate which triggers the creation of a class for the variables involved in the delegates code block. Consider the following code:

    class SomeClass
    {
        public int counter;
    
        public void DoSomething()
        {
            Console.WriteLine(counter);
            counter++;
        }
    }
    
    //... 
    
    List list = new List();
    
    for (int index = 0; index < 5; index++)
    {
        var instance  = new SomeClass { counter = index * 10 };
        list.Add(instance.DoSomething);
    }
    
    foreach (ThreadStart t in list)
    {
        t();
    }
    

    This code does exactly the same as in the original example. The variable instance is defined inside of the for loop, so its scope ends at every iteration, however it is not freed by the garbage collector since it is referenced by list. This is the reason why a class is created in case of anonymous delegates. You cannot do it otherwise.

提交回复
热议问题