This article refer to sikic# Advanced article, reproduced please indicate the source.
What is a delegate
If we want to pass the method as a parameter, we need to use the delegate. In a nutshell, a delegate is a type that can assign a reference to a method .
Declaring delegates and using
There are four ways of declaring a delegate. One is native, and the other three is C # for the convenience of encapsulation.
The four types of declarations are delegate, Action, Func,
Using a class in C # is divided into two stages, first defining the class, telling the compiler what fields and methods The class consists of, and then instantiating the object using this class. When we use the delegate, we also need to go through these two stages, first defining the delegate, telling the compiler what type we can point to the delegate, and then creating an instance of the delegate.
Delegate is defined and used in the following ways:
Delegate voidIntmethodinvoker (intx);Static voidTest1 (intx) {Console.WriteLine ("the int value is:"+x);}Static voidTest2 (strings) {Console.WriteLine ("The string value is:"+s);}Static voidMain () {Intmethodinvoker method=Test1; Method (); //The following actions are illegal//intmethodinvoker me = Test2;}
This delegate can only point to a method that has an int parameter with a return value of void, and the other methods cannot be pointed to. (not to be continued)
C # delegate, lambda expression, event