Create list of Actions with parameters and then execute it

1

I would like to create a list of Actions with parameters and then make a foreach in that list and exit executing the methods, each with their respective parameters.

Something more or less with the code below.

        private List<Action<int, int>> ListaAction = new List<Action<int, int>>();

    private int MetodoExecutar(int numero1, int numero2)
    {
        return numero1 + numero2;
    }

    private void MetodoMain()
    {
        int valor1 = 1;
        int valor2 = 2;

        ListaAction.Add(MetodoExecutar(valor1, valor2));
    }

    private void ExecutarListaDeActions()
    {
        foreach(Action acao in ListaAction)
        {
            acao();
        }
    }
    
asked by anonymous 21.02.2018 / 22:17

1 answer

5

Before answering, two remarks:

  • The delegate with return would be Func instead of Action ;
  • When you delegate a method, who 'supplies' the parameter values is the class that holds the invocation power of the delegate method;
  • If you understand these points (and trying to infer some meaningful fluctuation between the title of the question, the sample code presented and something that would be usable), it would look like this:

    private List<Func<int, int, int>> ListaDelegate = new List<Func<int, int, int>>();
    
    private int MetodoExecutar(int numero1, int numero2)
    {
        return numero1 + numero2;
    }
    
    private int MetodoExecutar2(int numero1, int numero2)
    {
        return numero1 * numero2;
    }
    
    private void MetodoMain()
    {
        ListaDelegate.Add(MetodoExecutar);
        ListaDelegate.Add(MetodoExecutar2);
        ListaDelegate.Add((num1,num2) => { return num1 * (num1 + num2); }); // Delegate anônimo
    }
    
    private void ExecutarListaDeActions()
    {
        int valor1 = 10;
        int valor2 = 20;
    
        foreach (Func<int, int, int> acao in ListaDelegate)
            System.Diagnostics.Debug.WriteLine("Resultado: " + acao(valor1, valor2).ToString());
    }
    

    Running the codes involved should print this out:

    // Resultado: 30
    // Resultado: 200
    // Resultado: 300
    
        
    21.02.2018 / 23:08