-1

I have to create a Dictionary of commands with the command (a string) being the key and the function the command is mapping to as the value. The problem I am facing is that the functions the commands are mapping to, have different amounts of parameters with different types.

How do I achieve this? Preferably, so that I can add the functions as lambda expressions.

Ex. dictionary.Add("square", x => x * x).

EDIT: All the mapped functions return void.

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
Kristian V.
  • 67
  • 1
  • 1
  • 7
  • 3
    How is this useful if the values have different types (`Func`, `Func` etc)? How do you know which type to cast the value to after you got the value by a key? – Sweeper May 02 '17 at 16:55
  • The commands are hardcoded, so I know which commands I need to add. It's an assignment for my exam, that requires me to map these functions to a dictionary. – Kristian V. May 02 '17 at 16:57
  • @K.Vestermark If you're just going to have the caller hard code things based on their fore-knowledge o the result, there's not point in using a generic data structure. – Servy May 02 '17 at 17:17
  • Dont think that this will be useful and it doesnt look like right approach. – loneshark99 May 02 '17 at 17:22
  • Short version: use base type `Delegate` as the value. At the call site, you'll either know at compile time the signature or not; if so, just include a compile-time cast to the right delegate type. If not, put the arguments in an array and call `DynamicInvoke()`. – Peter Duniho May 03 '17 at 03:45

1 Answers1

0

Why not using Dictionary<string, ICommand>. Here is the sample:

public class Command1 : ICommand
{
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        throw new NotImplementedException();
    }

    public void Execute(object parameter)
    {
        //user your first lambda here
    }
}

public class Command2 : ICommand
{
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        throw new NotImplementedException();
    }

    public void Execute(object parameter)
    {
        //use your second lambda here
    }
}

Then use them this way:

Dictionary<string, ICommand> dictionary = new Dictionary<string, ICommand>();

dictionary.Add("Command1", new Command1());

dictionary.Add("Command2", new Command2());
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116