Looping through a list of Actions

前端 未结 3 747
小鲜肉
小鲜肉 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:09

    This is a pretty complicated situation. The short answer is to create a copy of the local variable before assigning it to the closure:

    string copy = str;
    actions.Add(new Action(() => { Trace.WriteLine(copy); }));
    

    Check out this article on closures for more information.

提交回复
热议问题