- Named functions
- Anonymous methods
- Lambda expression
A delegate is a type that can store a reference as a function, define a delegate, declare a variable of that delegate type, and then initialize the variable to a function reference that has the same return type and argument list as the delegate, and then use the delegate variable to invoke the function, as if the variable were a function. After you have a variable that references a function, you can also perform an operation that cannot be done in other ways, such as passing a delegate variable as a parameter to a function so that the function can invoke any function it references by using a delegate, and you do not need to know which function to call before running.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacecsharprumenjd{classProgram {Delegate voidProcessdelegate (intnum); Static voidShowdouble (intnum) {num*=2; Console.WriteLine (num); } Static voidShowthree (intnum) {num*=3; Console.WriteLine (num); } Static voidShowfour (intnum) {num*=4; Console.WriteLine (num); } /// <summary> ///here, the delegate is passed as a parameter to the function,/// </summary> /// <param name= "Pro" ></param> /// <param name= "num" ></param> Static voidExcute (Processdelegate Pro,intnum) {Pro (num); } Static voidMain (string[] args) {Processdelegate Pro=NULL; stringinput =Console.ReadLine (); if(Input = ="D") Pro+ = showdouble;//the first method of correlation function Else if(Input = ="F") Pro= Showfour;//the second method of correlation function ElsePro=NewProcessdelegate (Showthree);//the third method of correlation functionExcute (Pro,1); Console.readkey (); } }}
The code shows three basic ways to delegate association naming methods
where + = can achieve Cumulative association Continuous association effect, that is, multiple calls to + =, the method of the delegate association in order to call all the associated methods;
Prior to C # 2.0, using named methods is the only way to instantiate a delegate. However, in later versions of c#2.0, when the overhead of creating a new method is unnecessary, you are allowed to instantiate the delegate and immediately specify the block of code that the delegate will process when it is called.
These are called anonymous methods,
A LAMBDA expression instantiates a delegate:
Resources:
on the common delegate in C #
Three stages of a delegate evolution in C #