简体   繁体   中英

Create function to add commands to custom program

I have previous experience in other programming languages but I have decided to try and work with some C#. I have been trying to find a way to create a function that will allow me to create other functions for commands

Example:

addCommand("help", public PrintHelp(){ Console.WriteLine("blah blah blah"); });

I am just not sure how to create the function so that it accepts another function as a parameter, and then can be called again.

Or I would like to be able to create a object that can save a function something like this:

Command Help = new Command;
Help.Function = public void printHelp() { Console.WriteLine("blah blah blah"); };
Help.Command = "help";

The second one would be ideal actually. I have tried only the first way by doing something like this:

public void AddCommand(string Command, delegate function){
  cmd = Command;
  FUNC = function;
}

I think you are looking for Action<T> and Function<T,Result> . Please refer to this post for example usage and here for MSDN documentation (the particular MSDN link provides lots of samples).

Essentially with Action<T> you can call a method using a lambda expression and hand in the Action<T> as an argument to another function (ie handing in a function as an argument). There are standard ways of doing this with C# using the delegate keyword but it is legacy functionality. If you are looking for the equivalent of a real function pointer then C# doesn't offer that construct directly (it is indirect by means of the delegate keyword). Hope this helps!

What you're asking for is known as the Command Pattern :

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Check out this simple C# implementation and also this nice tutorial .

C# exposes the types Action<T ... Tn> and Func<T ... Tn, TResult> for passing functions as arguments.

Action represents a void method call, while Func represents a delegate that returns a type TResult . Both classes have overloads that take an arbitrary number of parameters.

In your example, your addCommand signature would look like:

public void addCommand(string command, Action action);

You can then call it using a lambda expression:

addComand("help", () => { Console.WriteLine("blah blah blah") } );

or by passing in a method group:

public void printHelp()
{
  Console.WriteLine( "blah blah blah" );
}

// In calling code:
addCommand("help", printHelp);

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