简体   繁体   中英

Creating Dictionary with delegates

Would like to ask how to make a dictionary with delegate.

The idea is:

  1. Have a console based command defined by "/"
  2. use dictionary to store command and del that will invoke the function i need.

What i have so far: I managed to do same by creating events

delegate void CmdHandler(string[] cmdArgs);
    class CMDReader
    {


        public event CmdHandler _Print;
        public event CmdHandler _Help;

        private char cmdChar;
     }


cmdReader._Print += new CmdHandler(Print);
void Print(string[] args)

but I am looking for a way to manage it without event. I figured I can do so with dictionary but not sure how to do it.

You can add the delegates to a Dictionary , and then using an indexer key (I've just assumed the name of the command here) to Invoke the appropriate action. The problem with this pattern however is the loose typing on the arguments (All string[] , with implied knowledge about the meaning of each), and the restriction on a common return type from all methods (currently void ).

public class CMDReader
{
    delegate void CmdHandler(string[] cmdArgs); // Or Action<string[]>

    private readonly IDictionary<string, CmdHandler> _commands;
    public CMDReader()
    {
        _commands = new Dictionary<string, CmdHandler>
        {
            {
                "Print", Print
            },
            {
                "Help", Help
            },
        };
    }

    public void InvokeCommand(string command, string[] args)
    {
        if (_commands.ContainsKey(command))
        {
            _commands[command].Invoke(args);
            // OR (_commands[command])(args);
        }
        else
        {
            Console.WriteLine("I don't know that command ...");
        }
    }

    private void Print(string[] args)
    {
      // Implementation
    }
    private void Help(string[] args)
    {
      // Implementation
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM