Delegates are one of the most important features of C #, and almost all of C #’s subsequent features are built on them. A delegate in C# can be thought of as a wrapper around a function. A function in C# is passed as an argument, as opposed to a function pointer in C++.

The delegate definition is similar to the method definition, preceded by the delegate keyword. For example:

class Program { delegate void RunCmd(); Static RunCmd runcmd1; static runcmd1; Static RunCmd runcmd2; Static RunCmd runcmd3; static RunCmd runcmd3; Public static void runcmdExecute () {console.write (" Execute "); } public void RunCmdPause() { Console.Write("Puase"); } static void Main(string[] args) { runcmd1 = new RunCmd(RunCmdExecute); // create delegate object, static method //runcmd1 = runcmdExecute; // Runcmd1 = new Runcmd (new Program().RuncmdPause); // Runcmd1 += new Program().runcmdPause; // shortcut syntax runcmd1(); // Note that only the last "pause" is printed // runcmd2 = new Program().RunCmdPause; runcmd3 = runcmd1 + runcmd2; runcmd3(); // Print "executePuase" (); }}

In addition to calling a delegate like a method (like a function), there is an Invoke method that uses the delegate. Example: runcmd1. Invoke (); To invoke (someone, a theory, an instance, etc.); Note that the call delegate cannot be empty, otherwise an exception will be thrown.

if(runcmd1 ! = null) { runcmd1.Invoke(); } runcmd1 ? .Invoke(); // The invoke and conditional airlift operator syntax sugar is easy to use!

There are limits to how delegates can be wrapped

1) The front of the method is the same as the delegate, including the number of parameters, type, order.

2) The return type of the method should be the same as that of the delegate. The return type of the method is not part of the method signature.

A delegate can cause a method to be passed as an argument to another method.

We can see from the IL code that the nature of a delegate is a class.

Delegates in C # can also encapsulate multiple methods. C # calls a delegate that encapsulates multiple methods into a delegate chain or multicast delegate, a composite delegate. Note: If you combine delegates, only the value of the last method will be returned. There is no difference between a delegate with a reference argument and a method (function) with a reference. 7. Anonymous methods Anonymous methods do not require a separate method name

delegate void RunCmd(); // Declare delegate type RunCmd runcmd4 = delegate () // No arguments, or no arguments () can be omitted {console. Write(" anonymous method "); }; runcmd4();

Note: Anonymous methods do not display declared return values.

The Lambda operator => is pronounced as “goes to” and is placed between the argument list and the body of the function.

RunCmd runcmd5 =  ()=>

If the argument has only one and is of an implicit type, the parentheses may be omitted.