"Forwarding" when to use a delegate, why to use a delegate, what benefits

Source: Internet
Author: User

A lot of people have been asked: When to use the delegate, why to use the delegate, what is the benefit of the Commission ....

After reading the following article you will enlightened. (direct Tddtds that can not be understood)

Concept Although I don't like to talk too much

We directly first to yy a scene: I like playing games, but bad luck every time the game will be the director to see, Zhu Boss does not like his employees at work

Playing games, so Zhu Boss told the director: "After the staff in the game, you buckle him 20 dollars."

This is actually a commission, Zhu boss commissioned by the director once found that employees play games, do a thing.

How to write the program?

There are at least 2 classes, supervisors and employees, executives have a way to deduct money, employees have a way to play games, then began to work

Employee class:

 Public classEmployee {//Employee's salary       Private intMoney ; //the employee's supervisor       PrivateManager manager;  PublicEmployee (Manager manager) {//Initialize the employee's supervisor and salary through constructors. Manager =Manager; Money=8000; }        Public intMoney {Get{returnMoney ;} Set{Money =value;} }       Public voidPlayGame () {WriteLine ("Employee: Start playing the game ."); WriteLine ("staff: CS really fun, haha ha! I play ..."); Manager.removemoney ( This); }     }

Supervisor Class:

 Public classManager { PublicManager () {}//Deduction of Salary     Public voidRemovemoney (Employee employee) {WriteLine ("Supervisor: Dare to play games during work hours"); WriteLine ("Supervisor: Look at how much you pay for your kid:"+employee.       Money); WriteLine ("Supervisor: I started to deduct my salary ."); Employee. Money-= -; WriteLine ("Supervisor: Buckle up."); WriteLine ("Supervisor: Look at you, boy. Salary Surplus:"+employee.    Money); }  }

The Mian method probably says this:

 Public Static void Main (string[] args)  {     //  Generate object instance for Supervisor Class King     new  Manager ();      // to generate an object instance of an employee class class     Wind New Employee (king);      // employees start playing games Wind      . PlayGame ();  }

Run, and sure enough the result is right, it seems that as a programmer I still relatively low-key. It is normal and not complacent to write the results.

Employee: Start playing the game.
Staff: CS really fun, haha ha! I play ...
Supervisor: Dare to play games during work hours
Supervisor: Look at your little boy. Salary: 8000
Supervisor: I started to deduct my salary.
Supervisor: Buckle up.
Supervisor: Look at you, boy. Salary remaining: 7980

The following is a simple analysis of this program:

1: After creating the Supervisor class to create the employee class, the coupling is too high, that is to say you want to create an employee, you must first create a supervisor.

2: If the scene changes, I want to have the manager replace the supervisor, we have to modify the employee class, and add the manager class.

So it seems that this program is not good, we might as well consider the next event (special delegate) to achieve

You have to define a delegate to have the Supervisor monitor the employee, and then there is an event in the Employee class (the employee is the object that fired the event), and the supervisor executes the event

 Public Delegate voidPlay (Object Sender, System.EventArgs e); Public classEmployee { Public intMoney =2200;//too lazy to write attributes .         Public Eventplay play;  PublicEmployee () {} Public voidPlayGame () {System.EventArgs e=NewEventArgs (); Onplaygame ( This, E); }        voidOnplaygame (ObjectSender, EventArgs e) {            if(Play! =NULL) {Play (Sender, E); }        }    }

The Supervisor class is going to implement a method that, like the return of a delegate, is the same as a parameter, which is called by the delegate.:

 Public class Manager    {        public  Manager ()        {        }        publicvoid  Removemoney ( Object Sender, System.EventArgs e)        {            as  Employee;              - ;            System.Diagnostics.Debug.WriteLine (Emp.money);        }    }

Then the call becomes simple.

New Manager ();      // generate an object instance of the Employee class Shulin     New Employee ();       // set the delegate to specify the monitoring       New Play (Xiaotao. Removemoney);       // employees start to play games, play one time to buckle        e.playgame ();     E.playgame ();

Output:

2180
2160

Summary :

Of course, we can still design decoupled classes without using delegates and events, but it adds a lot of classes, interfaces, and associations, and so on, which increases the amount of code and the logic complexity of the program, while in. NET it takes a lot less code to implement the delegate and the event.

"Forwarding" when to use a delegate, why to use a delegate, what benefits

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.