Use of delegates and syntax definitions
The use of delegates is done in four steps, in order: declaring delegates, creating delegate objects, delegating association methods, calling
We use an example to illustrate how these four steps work, and we complete an example of how a boss commissioned an employee to write a report to see how it is implemented.
First of all, we should define two categories, boss bosses and employee class employees, the boss commissioned employees to write reports, in fact, the boss did nothing, but told the staff to do things (write a report),
So our definition is as follows
Public classBoss {//declaring a delegate Public Delegate voidDoworkeventhandler (stringcontent); //To create a delegate object PublicDoworkeventhandler Workeventhandler; //do things Public voidDoWork (stringcontent) { if(Workeventhandler! =NULL) {workeventhandler.invoke (content); //or call the following//handler (content); } }}
The Declaration and creation of a delegate are defined in the boss, and the DoWork internal only invokes the delegate, but at the moment it does not appear to be doing anything.
Another look at the implementation of employee class
Public class Employee { publicvoid DoWork (string content) { Console.WriteLine ( string. Format (" boss entrusts me {0}", Content)); } }
The DoWork method is defined in the employee class to accomplish exactly what
Then we'll see how the boss commissioned the employee to do something.
Public classDelegateexecutor { Public Static voidRun () {boss Boss=NewBoss (); stringContent ="Write a report"; //Delegate Registration Association methodBoss. Workeventhandler =NewBoss.doworkeventhandler (NewEmployee (). DoWork); //boss. DoWork (content); } }
Actually in the call boss. DoWork, the Employee.dowork method is called internally by the delegate. Okay, so we finally finish the job of the boss to entrust the staff to write the report function.
Benefits of Delegation
If we implement the above functions in a general way, we may write
Public class Boss { publicvoid DoWork (string content) { new Employee (); Employee. DoWork (content); } }
We see that there is a significant problem is that the boss and the employee class has a direct dependency, coupled together, but in the case of the implementation of the delegate, the boss does not know the existence of the employee,
Eliminating the coupling between the two is much better than the traditional notation.
I'll cover the use of events in the next article.
Understanding and application of the delegation of basic Learning in C #