Calling method by string command

Asked

Viewed 32 times

0

I am a command bar in an application with several functions present in buttons in a Ribon. A large part of these functions must be able to be executed by means of commands, for example:

Botão "Salvar" -> Método "Save()"

Comando "sv" -> Método "Save()"

I know it is possible to find the method by name and invoke it, but in this case the command will not have the same method name.

Is there any way in the method definition to define the command, as just below and invoke it through this command?

    [Command="sv"]
    private void Save()
    {
        // Save method
    }

1 answer

2


I do not know if there is a better way in WPF, but could use a dictionary with commands, See:

using System;
using System.Collections.Generic;

public class Program
{
        public static void Main()
        {
            //monta o dicionário com os comandos...
            cmd.Add("m1", () => { Metodo1(); });
            cmd.Add("m2", () => { Metodo2(); });


            ChamarMetodo("m1");
            ChamarMetodo("m2");

        }
        static Dictionary<string, Action> cmd = new Dictionary<string, Action>();

        static void ChamarMetodo(string cmd_key)
        {
            if (cmd.ContainsKey(cmd_key))
            {
                cmd[cmd_key].Invoke();
            }
        }

        static void Metodo1()
        {
            Console.WriteLine("metodo 1");
        }

        static void Metodo2()
        {
            Console.WriteLine("metodo 2");
        }
    
}

It is also possible to use an enumerator to have the commands including facilitating the development:

public class Program
{
        static Dictionary<ECmd, Action> cmd = new Dictionary<ECmd, Action>();

        public static void Main(string[] args)
        {
            cmd.Add(ECmd.Metodo1, () => { Metodo1(); });
            cmd.Add(ECmd.Metodo2, () => { Metodo2(); });


            ChamarMetodo(ECmd.Metodo1);
            ChamarMetodo(ECmd.Metodo2);

        }

        static void ChamarMetodo(ECmd cmd_key)
        {
            if (cmd.ContainsKey(cmd_key))
            {
                cmd[cmd_key].Invoke();
            }
        }

        static void Metodo1()
        {
            Console.WriteLine("metodo 1");
        }

        static void Metodo2()
        {
            Console.WriteLine("metodo 2");
        }
}

enum ECmd
{
    Metodo1,
    Metodo2
}
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.