如何结合几个Action< T>成为单个Action< T>在C#中? [英] how do I combine several Action<T> into a single Action<T> in C#?

查看:95
本文介绍了如何结合几个Action< T>成为单个Action< T>在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在循环中构建Action动作?解释(很长很抱歉)

How do I build an Action action in a loop? to explain (sorry it's so lengthy)

我有以下内容:

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

我可以用这两种方法调用它,而且效果很好:

I can call it with either of these and it works great:

var builder = new Builder();

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

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

How can I build the second implementation programmatically? i.e.,

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 

或类似的东西,但是对于我的一生,我没有看到如何构建自己想要的东西.任何想法将不胜感激!

or something similar, but for the life of me, I'm not seeing how to construct what I want. Any thoughts would be greatly appreciated!

推荐答案

这很容易,因为委托已经是多播的:

It's really easy, because delegates are already multicast:

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

或者如果您出于某些原因而收藏了它们:

Or if you've got a collection of them for some reason:

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

这篇关于如何结合几个Action&lt; T&gt;成为单个Action&lt; T&gt;在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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