You could use a dictionary that uses string
as keys and methods (either Action, Func or a custom delegate) as value, then you just need to reas the input from the user and use it a key key to get the corresponding action. If the command can have parameters like this command param1
then use string.Split
to separate the command from the parameter, then use the command string as key, and when you execute the method pass the other string as parameter (depending of the type of data of the parameter to may need to parse the parameter of the command from string to something else)
The code would look like this:
Using Func:
NOTE: Func
requires at least one parameter and a return value.
void Main()
{
public Dictionary<string, Func<string, int>> commands =
new Dictionary<string, Func<string, int>>();
commands.Add("getdate", GetDate);
Console.WriteLine("Enter a command");
string input = Console.ReadLine(); //<-- Try typing "getdate"
commands[input].Invoke();
}
public int GetDate(string someParameter)
{
Console.WriteLine(DateTime.Today);
return 0;
}
Using Action:
NOTE: Action
requires at least one parameter.
void Main()
{
public Dictionary<string, Action<string>> commands = new Dictionary<string, Action>();
commands.Add("getdate", GetDate);
Console.WriteLine("Enter a command");
string input = Console.ReadLine(); //<-- Try typing "getdate"
commands[input].Invoke();
}
public void GetDate(string someParameter)
{
Console.WriteLine(DateTime.Today);
}
Using Custom Delegate:
public delegate double YourDelegate(string param);
void Main()
{
public Dictionary<string, YourDelegate> commands =
new Dictionary<string, YourDelegate>();
commands.Add("getdate", GetDate);
Console.WriteLine("Enter a command");
string input = Console.ReadLine(); //<-- Try typing "getdate"
commands[input].Invoke();
}
public double GetDate(string someParameter)
{
Console.WriteLine(DateTime.Today);
return 0.0;
}