Delegation and events of pleasant goat and Big Wolf

Source: Internet
Author: User

I'm a beginner. net, the concept of delegation and events is vague. At that time, when reading a book, I could only understand the logic of the Code in the book, and know how to implement delegation and events with code, however, they have little understanding of the principles. When learning ASP. NET web page programming over the past few days, events and event parameters are mentioned many times. So I decided to re-understand the delegation and events.


To vividly describe the process of delegation and event implementation, I think of the story of pleasant goat and big wolf. I love watching cartoons, especially funny and mentally retarded cartoons like pleasant goat and Big Wolf and crayon. If you haven't read pleasant goat and Big Wolf, you can take a look at this opportunity.
To describe this story, we need to first establish two classes: Goat and Wolf.
// Wolf class code public class wolf {string name; // defines a variable used to store the wolf name // constructor public Wolf (string name) {This. name = Name;} public string name {get {return name;} set {name = value;} public void scare () // wolf has a threatening method {console. writeline ("Haha, I am {0}. Let me go back to Fort wolf! ", Name); console. writeline () ;}// goat class code public class goat {string name; // defines a variable for storing goat names // constructor public goat (string name) {This. name = Name;} public string name {get {return name;} set {name = value;} public void run () // Yang has an escape method {console. writeline ("Wolf is coming, {0} Run! ", Name); console. writeline ();}}
In the cartoon, every time the gray wolf sees the lambs, he first chats with the lambs, says something to scare the lambs, and then goes up to catch the lambs. At this time, the pleasant goat has long come up with a way to escape, no wonder every time the gray wolf cannot catch the sheep, he sees the sheep speak with them first and then acts.
If you don't talk nonsense, let's talk about how to use Commission and event implementation: the wolf scared the lambs and the lambs ran as soon as they heard it.
First of all, we need to understand the common sense: the wolf is stupid and won't tell the goat that I'm coming. Run fast. Therefore, the goat class objects cannot appear in the wolf class. That is to say, the run method of lambs cannot be written into the Scare method of the wolf. Wolf and goat cannot be associated, so we need to solve this problem through delegation.
A delegate is actually a reference to a method. Once a delegate is assigned a method, the delegate can be used like a method. The delegate defines the abstraction of the features of the method. The delegate and function can have parameters and return values. The format of the method allocated for the delegate must be consistent with that of the delegate, that is, the parameters and return values of the method must be the same as those of the delegate. A delegate can be seen as a "class" of a function. The function assigned to the delegate is the delegate instance.
First, we define a delegate.
public delegate void WolfScareEventHandler();    

Define a delegate without parameters and return values. The delegate name is wolfscareeventhandler. The delegate uses the keyword delegate declaration, which can be placed inside the wolf class or outside the class, because the delegate itself is also a "special class"
Then we define a wolfscareeventhandler delegate type event wolfscare

public event WolfScareEventHandler WolfScare;

The event is declared with the event keyword. The event must be declared inside the wolf class because the event belongs to the wolf class (we generally say that the class has three elements: attributes, events, and methods)
The wolf class code that contains the wolfscare event
Public class wolf {string name; // constructor public Wolf (string name) {This. name = Name;} public string name {get {return name;} set {name = value ;}}// declare an event of the wolfscareeventhandler delegate type public event wolfscareeventhandler wolfscare; public void scare () {console. writeline ("Haha, I am {0}. Let me go back to Fort wolf! ", Name); // the following code triggers the wolfscare event if (wolfscare! = NULL) {wolfscare ();}}}


In this way, the wolf class has an event, and the current event is triggered when the wolf executes the scare method. If a method is assigned to the event, the method is executed.
The most important thing is to look at the main program code:

Static void main (string [] ARGs) {wolf bigwolf = new wolf ("grey Wolf"); // declare a wolf Class Object bigwolf, the name is "grey Wolf" // declare three goat objects goat happygoat = new goat ("Pleasant goat"); goat lazygoat = new goat ("lazy goat "); goat stronggoat = new goat ("Boiling goat"); // The bigwolf Method for event allocation. wolfscare + = new wolfscareeventhandler (happygoat. run); bigwolf. wolfscare + = new wolfscareeventhandler (lazygoat. run); bigwolf. wolfscare + = new wolfscareeventhandler (stronggoat. run); bigwolf. scare ();}

In the main program, three methods are assigned for the event wolfscare of the bigwolf object: happygoat. Run, lazygoat. Run, and stronggoat. Run. The advantage of using delegation is that the goat class does not appear in the wolf class, but dynamically allocates methods for events in the main program. These methods can be methods of different objects, as long as the format is consistent with the delegate type.
In this way, when bigwolf executes the scare method, the event wolfscare will be triggered and the three methods of happygoat. Run, lazygoat. Run, and stronggoat. Run will be executed. The running result is as follows:

Some people will say that the control event process in. Net generally includes parameters, as shown below:

protected void Button1_Click(object sender, EventArgs e)        {                    }
This event process includes two parameters: sender and E, which are of the object type and eventargs type. Sender refers to the object in which the event is triggered. Here, it is button1; E is an event parameter, which carries some data related to this event.
Then we will transform the code of "pleasant goat and Big Wolf" so that its events will also contain parameters.
First, define an event parameter class wolfscareeventargs to inherit the eventargs class.
Public class wolfscareeventargs {string name; // defines a name variable to store the name of a wolf, in this way, the event parameter can carry the wolf's name public string name {get {return name;} set {name = value ;}}}
Delegate Transformation: The event process (that is, the delegate allocation method) carries parameters.
public delegate void WolfScareEventHandler(object sender,WolfScareEventArgs e);
Transformed wolf class
Public class wolf {string name; // constructor public Wolf (string name) {This. name = Name;} public string name {get {return name;} set {name = value ;}}// declare an event of the wolfscareeventhandler delegate type public event wolfscareeventhandler wolfscare; public void scare () {console. writeline ("Haha, I am {0}. Let me go back to Fort wolf! ", Name); console. writeline (); // the following code triggers the wolfscare event if (wolfscare! = NULL) {// define an event parameter object wolfscareeventargs ARGs = new wolfscareeventargs (); args. name = This. name; // assign the wolf name to the name attribute wolfscare (this, argS) of the event parameter;} // rewrite the tostring method so that sender. tostring () is used to display the public override string tostring () {return this. name ;}}


The code of the goat class should also be transformed:

Public class goat {string name; // constructor public goat (string name) {This. name = Name;} public string name {get {return name;} set {name = value;} public void run (Object sender, wolfscareeventargs e) {console. writeline ("{0} is coming, {1} Run! ", E. name, name); // here, the name attribute of parameter E can be used to show which wolf comes to the console. writeline ("The Wolf chasing me is:" + sender. tostring (); // you can use the tostring method of the sender object to display the name of the wolf that triggers the event. writeline ();}}
The main program does not need to be changed. To facilitate the demonstration, we changed the name of the wolf to "Red Wolf"
Static void main (string [] ARGs) {wolf bigwolf = new wolf ("Red Wolf"); goat happygoat = new goat ("Pleasant goat "); goat lazygoat = new goat ("lazy goat"); goat stronggoat = new goat ("Boiling goat"); // Add the bigwolf Method to the event. wolfscare + = new wolfscareeventhandler (happygoat. run); bigwolf. wolfscare + = new wolfscareeventhandler (lazygoat. run); bigwolf. wolfscare + = new wolfscareeventhandler (stronggoat. run); bigwolf. scare ();}

Program running effect:





Many people may think that the events mentioned above are not the same as the control events in. net. In fact, their principles are the same:
When we double-click a control, the Code Editor automatically writes an event processing process for us.

protected void Button1_Click(object sender, EventArgs e)        {                    }
In fact, the button#click method is similar to the run method of the goat class mentioned above. The button1_click process is behind the event button1.click, which is similar to the bigwolf. wolfscare event above. In fact, button#click can be a casual name, such as fun (Object sender, eventargs E), as long as you add the following statement to the Code:
Button1.Click+=New EventHandler(fun);

In this way, when the click event of button1 is triggered, the fun method is executed. You can assign any number of methods to the button1.click event. When an event is triggered, these methods will be executed.
The event process you see is similar to protected void button#click (Object sender, eventargs e). This is because when you double-click a control, the system automatically creates the protected void button#click (Object sender, eventargs E) and assigns it to the event button1.click. you can also assign the event process of other controls to the event button1.click, for example:

Protected void textbox1_textchanged (Object sender, eventargs e) {response. Write ("this is the event process of the text box");} button1.click + = new eventhandler (textbox1_textchanged)
In this way, click button1, And the textboxmediatextchanged event process will also be executed. In short, the event process is the same as the general function and method, except that the system assigns it to the event and executes the allocated event process when the event is triggered.

Do you understand the principle of the event?


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.