Principle: Similar to function pointers in C and C + +.
Statement: Using the delegate keyword
public delegate void Del (String message);
Construct: Provide the name of the method you want to wrap or use the anonymous method
Method 1: Provide the method name
1, first define a method to be packaged:
Create a function for a delegate
public static void Delegatemethod (String message)
{
System.Console.WriteLine (message);
}
2. Construct a delegate with the name of the method
Initializing delegates
Del handler = Delegatemethod;
Invoke delegate
Handler ("Hello world!");
Method 2: Build with anonymous method
Directly initialize the delegate and invoke it:
Initializing delegates
Del handler = delegate (String message) {System.Console.WriteLine (message);
Invoke delegate
Handler ("Hello world!");
Execution: The parameter that the caller passes to the delegate is passed to the method, and the return value from the method, if any, is returned to the caller by the delegate.
A delegate can wrap multiple methods
Public unsafe delegate int Del (int* i);
public unsafe static int DelAdd1 (int* i)
{
*i + 1;
return 1;
}
public unsafe static int DelAdd2 (int* i)
{
*i + 1;
return 2;
}
public unsafe static int DelAdd3 (int* i)
{
*i + 1;
return 3;
}
Call it in another method
Unsafe
{
int result;
int i = 10;
Del handler1 = DelAdd1;
Del handler2 = DELADD2;
Del Handler3 = DelAdd3;
Del Allhandler = handler1 + Handler2 + handler3;
result = Allhandler (&i);
System.Console.WriteLine ("I am:" + i + ", and result is:" + result);
}
Operation results: I is:13,and result is:3
Visible: When wrapping multiple methods, all methods are called sequentially. If the delegate uses a reference parameter, the reference is passed to each of the three methods in turn, and the changes caused by one method are visible to the next method. If the delegate has a return value and/or an output parameter, it returns the return value and parameters of the method that was last called.
Exception when multiple method calls:
If either method throws an exception, and the exception is not caught within the method, the exception is passed to the caller of the delegate and no longer calls the method later in the invocation list.
Add and remove packaging methods:
Add can use +,+=, to remove a method from the invocation list, use the subtraction operator or the subtraction assignment operator ("-" or "=").