3/27/2017
using System;
using System.Collections.Generic;
/* This example shows one way of using delegates in a command parser
* The final output of this example will be
* doHello function called.
* doWorld function called.
* doThere function called.
* doWorld function called.
*
* Notice in this example the delegate and the associated functions don't accept any parameters.
* Delegates don't have to have parameters, infact, they can also have a return value
*/
namespace DelegatesTutorial
{
// Declare the delegate to be used later, this sets the return type and expected parameters
// for the delegate. All functions to be included must have the same return type and parameter list.
delegate void myDelegate();
// Declare a class to contain the keyword and the delegate
class Command
{
public string Keyword = default(string);
public myDelegate CmdPointer;
public Command(string sKeyword, myDelegate dPointer)
{
Keyword = sKeyword;
CmdPointer = dPointer;
}
}
class Example3
{
// Instead of creating a list of delegates, we'll create a list of the command class
List<Command> Commands = new List<Command>();
public Example3()
{
// We'll now add three commands
Commands.Add(new Command("hello", new myDelegate(doHello)));
Commands.Add(new Command("there", new myDelegate(doThere)));
Commands.Add(new Command("world", new myDelegate(doWorld)));
// Let's use the command parser
CommandParser("Hello");
CommandParser("world");
CommandParser("there");
CommandParser("world");
}
// Here's the actual command parser. It simply compares text then calls the
// appropriate function through the delegate
void CommandParser(string CommandToParse)
{
foreach (Command c in Commands)
{
if (c.Keyword.ToLower() == CommandToParse.ToLower())
c.CmdPointer();
}
}
// These are the functions to be called by the delegate
void doHello()
{
Console.WriteLine("doHello function called.");
}
void doThere()
{
Console.WriteLine("doThere function called.");
}
void doWorld()
{
Console.WriteLine("doWorld function called.");
}
}
}