Reproduce Capturing iteration variable issue

前端 未结 3 999
时光取名叫无心
时光取名叫无心 2021-01-22 20:01

I\'m rereading a part from c# 5.0 in Nutshell about the capturing iteration variables (Page 138) and I have tried to reproduce the code bellow on c# 4.0 and c# 5.0 but with n

3条回答
  •  被撕碎了的回忆
    2021-01-22 20:19

    This behavior had been changed for foreach loops since 4.0. But you can reproduce it with a for loop:

    static void Main()
    {      
        Action[] actions = new Action[3];
        int i = 0;
        for (var c = 0; c < 3; c++)
            actions[i++] = () => Console.Write(c);
        for (int j = 0; j < 3; j++)
        {
            actions[j]();
        }
        foreach (Action a in actions) a();    
        Console.ReadLine(); 
    }
    

    Output: "333333"

提交回复
热议问题