C # understanding and application of basic learning delegation,
Use of delegation and syntax definition
The use of the delegate is completed in four steps: declare the delegate, create the delegate object, delegate association method, and call
We will use an example to illustrate how these four steps are implemented. We will complete an example for the boss to entrust employees to write reports and see how to implement them.
First, we should define two classes: Boss and Employee. The Boss entrusts the Employee to write a report. In fact, the Boss did not do anything, but told the Employee to do things (write a report ),
The definition is as follows:
Public class Boss {// declare the delegate public delegate void DoWorkEventHandler (string content); // create the delegate object public DoWorkEventHandler WorkEventHandler; // do things public void DoWork (string content) {if (WorkEventHandler! = Null) {WorkEventHandler. Invoke (content); // or the following call // handler (content );}}}
The declaration and creation of delegation are defined in the Boss. DoWork calls the delegate internally, but it cannot be seen at present.
Let's look at the implementation of employee classes.
Public class Employee {public void DoWork (string content) {Console. WriteLine (string. Format ("My boss entrusted me {0}", content ));}}
The employee class defines the DoWork method to implement specific things.
Next, let's look at how Boss entrusts the Employee to do things.
Public class DelegateExecutor {public static void Run () {Boss boss = new Boss (); string content = "Write report"; // delegate registration association method boss. workEventHandler = new Boss. doWorkEventHandler (new Employee (). doWork); // boss. doWork (content );}}
In fact, when calling boss. DoWork, the internal delegate calls the Employee. DoWork method. Now, we can finally complete the report writing function entrusted by the boss to employees.
Delegate advantages
If we implement the above functions in general writing, we may write
public class Boss { public void DoWork(string content) { Employee employee = new Employee(); employee.DoWork(content); } }
We can see that there is a significant problem in this regard: the Boss and the Employee class have a direct dependency and are coupled together. However, in the delegated implementation example, the Boss does not know the existence of the Employee,
Eliminate the coupling between the two, is it much better than traditional writing.
In the next article, I will introduce how to use events.