在C#中如何将几个Action组合成一个Action?

前端之家收集整理的这篇文章主要介绍了在C#中如何将几个Action组合成一个Action?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在循环中构建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

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

解决方法

这很简单,因为代理已经是多播了:
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());
原文链接:https://www.f2er.com/csharp/94827.html

猜你在找的C#相关文章