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 code (simplified example):
string[] strings = { "abc", "def", "ghi" };
var actions = new List<Action>();
foreach (string str in strings)
actions.Add(new Action(() => { Trace.WriteLine(str); }));
foreach (var action in actions)
action();
Output:
ghi
ghi
ghi
Why is it always selecting the final element in strings
when it performs the action?
And how can I achieve the desired output which would be:
abc
def
ghi
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…