加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:44:14 所属栏目:百科 来源:网络整理
导读:如何在循环中构建Action动作?解释(对不起,太长了) 我有以下几点: public interface ISomeInterface { void MethodOne(); void MethodTwo(string folder);}public class SomeFinder : ISomeInterface { // elided } 和一个使用上述的课程: public Map Buil
如何在循环中构建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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读