Delegate: is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method that has a compatible signature. You can invoke a method from a delegate instance.
The above is an official statement, it is difficult to understand, to give an example of life:
Someone has three sons, let them each take one thing to go out, and bring back a prey.
The above sentence can be understood as the father's Commission on his son: Prey method (Tool tool)-->delegate prey (return value) bring back prey (delegate name) (tool (parameter type) x)-->delegate int GetValue (int i )
Three people perform delegates in different ways
Rabbit Hunting (tool bow)-public static int GetValue1 (int i) {return i;}
Pheasant Buy (tool money)-public static int GetValue2 (int i) {return i*2;}
Wolf Trap (tool trap)-public static int GetValue3 (int i) {return i*i;}
How to invoke a delegate
A delegate object is generated with the New keyword (the method name as a parameter), and the Association of the delegate to the method is established.
GetValue obj = new Getvlaue (class.getvalue1);
obj (3); -Result:3
GetValue obj = new Getvlaue (class.getvalue2);
obj (3); -Result:6
GetValue obj = new Getvlaue (CLASS.GETVALUE3)
obj (3); -Result:9
Call different methods by delegate, use the method that you want to execute as the argument of the delegate
We can also implement multicast delegation , what is multicast delegation, see Example:
GetValue obj = new Getvlaue (class.getvalue1);
obj + = new Getvlaue (class.getvalue2);
obj + = new Getvlaue (CLASS.GETVALUE3);
obj (3);
A multicast delegate is a call to a delegate, and all associated methods are called.
Benefits of Delegation
1. Equivalent to using a method as another method parameter (similar to the C function pointer)
2. As a bridge between two methods that cannot be called directly, such as: a cross-threading method call in a multi-thread will have to be delegated
3. Use a delegate when you do not know what the method specifically implements, such as: Using a delegate in an event
Attached: The delegate is encapsulated in the. NET Framework, using func<> directly instead of the overloads with up to four parameters for delegate,func<>.
Understanding delegates (delegate) and why delegates are used