how do I combine several Action into a single Action in C#?

后端 未结 1 1623
太阳男子
太阳男子 2021-02-07 02:41

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

I have the following:

public interface ISomeInterface {
    void MethodOn         


        
相关标签:
1条回答
  • 2021-02-07 03:08

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

    Or even:

    IEnumerable<Action<ISomeInterface>> actions = GetActions();
    Action<ISomeInterface> action = (Action<ISomeInterface>)
        Delegate.Combine(actions.ToArray());
    
    0 讨论(0)
提交回复
热议问题