The first time I came into contact with delegation in programming languages, I felt very unfamiliar. After several examples, we found that the delegation in the object-oriented language is the same as in our real life. For example, Xiaohong needs to go to the bank to get the money. Here, it is the method of Xiaohong. Similarly, if James is, he can also get the money. If Xiao Hong asks Xiao Ming to take money for her due to some issues, it is delegated here. That is, James uses the same method to get money in the name of Xiaohong.
In C #, the Delegate is derived from the base class System. delegate. However, the Delegate definition is different from the conventional definition method. The delegate is defined by the keyword Delegate:
Public delegate void myDelegate (int x, int y)
The code above defines a new delegate, which can encapsulate any method that returns an int with two int parameters, whether it is an instance method or a static method, as long as their signatures (the order of parameter types in a method) are the same as the defined delegate, they can be encapsulated into the delegate.
Here is a specific example:
For ease of understanding, I declare a specific class here.
Public delegate void GetMoney (string name); // defines the delegate class Example2 {public static void getCCBmoney (string name) {Console. WriteLine ("get money from CCB! ");} Public static void getABCmoney (string name) {Console. WriteLine (" get the money from ABC! ");} Static void Main (string [] agrs) {GetMoney gm; gm = getABCmoney; // delegate instantiation, Or you can write it as GetMoney gm = new GetMoney (getABCmoney) gm ("Xiaohong ");}}
The output result is as follows:
From the above example, we can sum up that a delegate is a class that defines the type of the method and can pass the method as a parameter. This dynamic parameter-based approach is assigned, this greatly improves program scalability.