Looping through a list of Actions

前端 未结 3 752
小鲜肉
小鲜肉 2020-12-11 03:12

I can\'t understand how to loop through an Action list. When I try it, I end up with the values being the same as the previous iteration.

Here\'s the co

3条回答
  •  余生分开走
    2020-12-11 04:01

    Your action is a closure, therefore it accesses str itself, not a copy of str:

    foreach (string str in strings)
    {
        var copy = str; // this will do the job
        actions.Add(new Action(() => { Trace.WriteLine(copy); }));
    }
    

提交回复
热议问题