如何将多个Action <t>组合成C#中的单个Action <t>?</t> </t>

时间:2010-04-01 10:51:34

标签: c# lambda

如何在循环中构建Action操作?解释(对不起,这太长了)

我有以下内容:

public interface ISomeInterface {
    void MethodOne();
    void MethodTwo(string folder);
}

public class SomeFinder : ISomeInterface 
{ // elided 
} 

以及使用上述内容的类:

public Map Builder.BuildMap(Action<ISomeInterface> action, 
                            string usedByISomeInterfaceMethods) 
{
    var finder = new SomeFinder();
    action(finder);
}

我可以用其中任何一种来调用它,效果很好:

var builder = new Builder();

var map = builder.BuildMap(z => z.MethodOne(), "IAnInterfaceName");
var map2 = builder(z =>
                   {
                     z.MethodOne();
                     z.MethodTwo("relativeFolderName");
                   }, "IAnotherInterfaceName");

如何以编程方式构建第二个实现?即,

List<string> folders = new { "folder1", "folder2", "folder3" };
folders.ForEach(folder =>
               {
                 /* do something here to add current folder to an expression
                  so that at the end I end up with a single object that would
                  look like:
                  builder.BuildMap(z => {
                                   z.MethodTwo("folder1");
                                   z.MethodTwo("folder2");
                                   z.MethodTwo("folder3");
                                   }, "IYetAnotherInterfaceName");
                */
                });

我一直以为我需要一个

Expression<Action<ISomeInterface>> x 

或类似的东西,但对于我的生活,我没有看到如何构建我想要的东西。任何想法都将不胜感激!

1 个答案:

答案 0 :(得分:28)

这很简单,因为代表已经是多播:

Action<ISomeInterface> action1 = z => z.MethodOne();
Action<ISomeInterface> action2 = z => z.MethodTwo("relativeFolderName");
builder.BuildMap(action1 + action2, "IAnotherInterfaceName");

或者,如果你出于某种原因收集了它们:

IEnumerable<Action<ISomeInterface>> actions = GetActions();
Action<ISomeInterface> action = null;
foreach (Action<ISomeInterface> singleAction in actions)
{
    action += singleAction;
}

甚至:

IEnumerable<Action<ISomeInterface>> actions = GetActions();
Action<ISomeInterface> action = (Action<ISomeInterface>)
    Delegate.Combine(actions.ToArray());