通过操作列表循环 [英] Looping through a list of Actions

查看:136
本文介绍了通过操作列表循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白如何通过一个动作列表循环。当我尝试它,我最终的值是一样的前一次迭代



下面的代码(简化的例子):

 字符串[]字符串= {ABC,高清,GHI}; 

变种行动=新的List<作用>();
的foreach(字符串中的字符串str)
actions.Add(新动作(()=> {Trace.WriteLine(STR);}));

的foreach(以行动VAR行动)
动作();



输出:

  GHI 
GHI
GHI

为什么总是选择在字符串的最后一个元素时,它执行的操作结果
和我怎样才能达到理想的输出这将是:

  ABC 
DEF
GHI


解决方案

您的行动是一个封闭,因此访问 STR 本身,而不是一个副本 STR

 的foreach(字符串中的字符串str)
{
VAR副本= str中; //这将做的工作
actions.Add(新动作(()=> {Trace.WriteLine(复印件);}));
}


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

解决方案

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); }));
}

这篇关于通过操作列表循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆