Tag: Call the color console to understand the keyword variable Hello logs wrapper
Basic steps
(1) Defining a delegate type, which defines a definition similar to a method, is just one more delegate;
(2) Instantiation of the delegate, the delegate is also a class type, so use the New keyword is also instantiated;
The instantiation of a delegate takes a method name as a parameter, and the definition of the method must conform to the definition of the delegate;
The number of arguments, the type of the parameter, the return type, and the delegate
(3) The object that is instantiated by the delegate is passed to other methods or directly executes the delegate (in essence, the method of executing the delegate wrapper);
A C # delegate can be understood as a wrapper for a function, and he can pass the method as a parameter to another method
Cases:
1 classHelloWorld2 {3 //Define the delegate type, which defines the definition of a similar method, just a delegate;4 Delegate voidMyDelegate (intAintb);5 Static voidMain (string[] args)6 {7 //declaring and instantiating delegate variables8MyDelegate mydelegate=NewMyDelegate (NewHelloWorld (). ADD);9 //passing an instantiated object MyDelegate as a parameter to a methodTen NewHelloWorld (). Go (mydelegate); One Console.readkey (); A } - voidADD (intA=0,intb=0) - { theConsole.Write ("This sum is {0}", A +b); - } - Private voidGo (mydelegate mydelete) - { + //invoking a delegate in a method -Mydelete (Ten, -); + } A}
The result is:
C # Delegate