我無法理解如何遍歷Action
列表。當我嘗試它時,我最終得到的值與之前的迭代相同。循環顯示一系列操作
下面的代碼(簡化的示例):
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();
輸出:
ghi
ghi
ghi
爲什麼總是選擇最終元件中strings
時所執行的操作?
我怎樣才能達到理想的輸出具體做法是:
abc
def
ghi
嘎,你贏了。我知道如何解決這個問題,但我不記得原因。關閉!我需要關閉! +1 :) – Joshua 2012-03-05 15:37:25
@Joshua這是不是很久以前,當我更深入地瞭解到:)這可能是進一步閱讀好http://stackoverflow.com/questions/9412672/lambda-expressions-with -m-cult -reading-in-c- – 2012-03-05 15:39:42
有趣的是,我從來沒有意識到。謝謝。 – demoncodemonkey 2012-03-05 15:46:20