The first thing to know is what a delegate is, and the delegate is actually equivalent to a function pointer in the C language
A declaration delegate
Example: Delegate void Stringprocessor (string input);
This is a delegate declaration with a null return value, where the declared argument must be of type string, and the return type is compared (the type must match the type of the return value of the method the delegate points to);
Two example of creating a delegate
Example:
Jonprocessor = new Stringprocessor (Jon. Say);
Tomprocessor = new Stringprocessor (Tom. Say);
Backgroung = new Stringprocessor (background.note);
If the delegate operates on a static method, the direct operation is OK, if the method of the instance of the delegate operation must first create the instance of the method
(Note: If the delegate instance itself cannot be retracted, the delegate instance will prevent its target from being garbage collected, which can cause significant memory leaks (leak))
Three-invocation delegate
Example:
void Invke (string input);
The delegate instance can be invoked only by passing in the parameters required by the original method.
Four complete examples
Using System;namespace consoleapplication1{delegate void Stringprocessor (string input); Class Perosn {string name; Public perosn (string name) {this.name = name;} public void Say (String message) {Console.WriteLine ("{0} says: {1}", name,message); }} class Background {public static void note (String note) {Console.WriteLine ("({0})", Note); }} class Program {static void Main (string[] args) {perosn jon = new Perosn ("Json"); Perosn tom = new Perosn ("Tom"); Stringprocessor jonprocessor, Tomprocessor, Backgroung; Jonprocessor = new Stringprocessor (Jon. Say); Tomprocessor = new Stringprocessor (Tom. Say); Backgroung = new Stringprocessor (background.note); Jonprocessor ("hi!son!"); Tomprocessor.invoke ("hi! Daddy "); Backgroung ("An airplane flies past!"); } }}
Beginner's Commission