A delegate is a type-safe object that points to another method (or methods) that will be called later in the program. In layman's words, a delegate is an object that can refer to a method, and when a delegate is created, an object that references the method is created, and the method can be called, that is, the delegate can invoke the method it refers to.
How do I use a delegate?
1. Defining delegate types
[Access modifier]delegate return type delegate name (formal parameter);
2. Declaring a Delegate object
Delegate name delegate instance name;
3. Create a Delegate object (determine which methods to bind to)
Delegate instance name =new delegate name (method of a class)
4. Using delegate invocation method
Delegate instance name (argument)
Considerations for Delegation:
1. Delegates and methods must have the same parameters.
2, delegates can call multiple methods, that is, a delegate object can maintain a list of callable methods instead of a separate method called multicast (multicast).
3. The method is increased and decreased by using the + = and-= operations.
4, the event is also a special delegate
Instance:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingDelegate;namespacedelegate{ Public Delegate intCall (intNUM1,intNUM2);//First step: Define the delegate type classSimpleMath {//Multiplication Method Public intMultiply (intNUM1,intnum2) { returnNUM1 *num2; } //Division Method Public intDivide (intNUM1,intnum2) { returnNUM1/num2; } }}classtest{Static voidMain (string[] args) {Call objcall;//Step Two: Declare the delegate object//object of the Math classSimpleMath Objmath =NewSimpleMath (); //Step Three: Create a delegate object and associate the method with the delegateObjcall =NewCall (objmath.multiply); Call ObjCall1=NewCall (objmath.divide); Objcall+ = OBJCALL1;//add a method to a delegate//Objcall-= objCall1;//subtract a method from a delegate//invokes the delegate instance, executes objmath.multiply first, and then executes Objmath.divide intresult = Objcall (5,3); System.Console.WriteLine ("The result is {0}", result); Console.readkey (); }}
C # notes--delegates