Original article address: Delegates and Events in C #/. NET
Delegate)
The delegate function in C # is similar to the pointer function in C/C ++. With delegation, programmers can pass references to methods in the delegate object. The delegate object is passed to the code that calls the reference method, instead of calling the method during compilation.
Direct method call-do not use Delegation
In most cases, when we need to call a method, we call the specified method directly. If there is a method Process for the class MyClass, we usually use this method to call (SimpleSample. cs ):
1 using System;
2
3 namespace Akadia. NoDelegate
4 {
5 public class MyClass
6 {
7 public void Process ()
8 {
9 Console. WriteLine ("Process () begin ");
10 Console. WriteLine ("Process () end ");
11}
12}
13
14 public class Test
15 {
16 static void Main (string [] args)
17 {
18 MyClass myClass = new MyClass ();
19 myClass. Process ();
20}
21}
22}
In most cases, there is no problem. However, sometimes we do not want to call methods directly, but are more willing to upload them to other places so that they can be called. When a user clicks a button, and I want to execute some code, the delegate is quite useful for event-driven systems like GUI.
Very simple Delegation
An interesting and useful attribute of a delegate. It does not need to know or care about the objects of the class it references. Any object can do this. The problem is that the parameter type and Return Value Type of the method must match the parameter type and Return Value Type of the delegate. This makes the delegate perfect for "anonymous" calls.
The statement format of unicast delegation is as follows:
Delegate result-type identifier ([parameters]);
Where:
Result-type: The result type, which matches the return type of the function.
Identifier: The delegate name.
Parameters: The Parameters, that the function takes.
For example:
Public delegate void SimpleDelegate () This Declaration defines a delegate named SimpleDelegate, which can pass any method without parameters or return values. |
Public delegate int ButtonClickHandler (object obj1, object obj2) This statement defines the delegate named ButtonClickHandler, which can be passed to any method that contains two objects and returns an integer value. |
To be continued...