[C # Basic Knowledge series] Topic 4: Revealing events

Source: Internet
Author: User

Introduction:

The previous topics described delegation in detail, and we often hear the concept of "Event" during code writing, especially when writing the UI, when we click a button, Vs will automatically generate some background code for us. Then we only need to write the code in the click method, so some of my friends who are new to C # may feel that this is a matter of course and have not thought about why, why does clicking an event trigger the code written in the click method? What role does an event assume? To relieve these questions, we will introduce the event in detail below, so that some beginners can understand the concept of the event in C.

I. Why is there an event in C?

The previous topic introduced why I understand the need for delegation, so here I will share my understanding about why the concept of event should be introduced in C. The following is an example of an event in my life. When my birthday is just over, I want to talk about it on my birthday, when the date of the birthday arrives, the birthday event is triggered. At this time, the person who has the birthday is the object that triggers the birthday event, then your friends will pay attention to this event. Once this event is triggered, they may celebrate your birthday with you and then give you a gift, of course, not everyone will pay attention to your birthday. Some people will not know it at all. Only those who have followed your birthday event will give you a gift. This is a birthday process in our life. However, we certainly have a better understanding of the concept of event in C #. C # is an object-oriented language, we use the C # language for coding to help us accomplish things in real life, so of course there must beEventTo reflect what happened in your life.

2. How do I implement an event model?

Now we know why C # introduces events, but most of the events we use in code are. net Class Library provides us with, for example, various events of the control, we only need to click the button to trigger the click event, but we really want to understand how this event is triggered, can we define a program that implements the event mode by ourselves? The answer is yes, of course. The following describes how to implement an event pattern through code.

The Code is as follows:

Using system; using system. threading; namespace birthdayeventdemo {class program {static void main (string [] ARGs) {// instantiate an event source object me eventsource = new me ("learning hard "); // instantiate the object friend1 obj1 = new friend1 (); friend2 obj2 = new friend2 (); // use the delegate to register the object and its method to eventsource in the event. birthdayevent + = new birthdayeventhandle (obj1.sendgift); eventsource. birthdayevent + = new birthdayeventhandle (obj2.buycake );// When the event reaches the trigger birthday event, the event calls eventsource. timeup (); console. read () ;}// Step 1: Define a type to save all additional information that needs to be sent to the event receiver public class birthdayeventargs: eventargs {// indicates the name of the birthday owner private readonly string name; Public string name {get {return name;} public birthdayeventargs (string name) {This. name = Name ;}// Step 2: Define a birthday event. First, define a delegate type, public Delegate void birthdayeventhandle (Object sender, birthday Eventargs E); // defines the event member public class subject {// defines the birthday event public event birthdayeventhandle birthdayevent; // Step 3: defines a method for triggering the event, it notifies the concerned object (notifies my friends) protected virtual void Policy (birthdayeventargs e) {// for thread security considerations, now copy the reference to the delegate field to a temporary field with birthdayeventhandle temp = interlocked. compareexchange (ref birthdayevent, null, null); If (temp! = NULL) {// trigger the event, which is used in the same way as the method. // event notification delegate object. Delegate object calls the encapsulated method temp (this, e );}}} // define the object for triggering the event. The event source is public class me: Subject {private string name; Public me (string name) {This. name = Name;} public void timeup () {birthdayeventargs eventarg = new birthdayeventargs (name); // notify friends of this. Y (eventarg) ;}// friend object public class friend1 {public void sendgift (Object sender, birthdayeventargs e) {console. writeline (E. name + "birthday, I want to give a gift") ;}} public class friend2 {public void buycake (Object sender, birthdayeventargs e) {console. writeline (E. name + "My birthday is coming. I want to buy a cake ");}}}

The running result is:

3. How does the compiler interpret events?

We have introduced how to implement an event mode by yourself. You can expand the code to view it in detail, the main implementation process is to define the event source of the trigger object (who has a birthday)-> define the friend object that follows your birthday event-> register the method to pay attention to the event, when an event is triggered, the notification registration method is called. However, I believe there are still some questions-what is the event in C? How does the compiler explain it? The following are some of your questions:

FirstEventActuallyDelegate(To be exactAn event is a delegate chain.In the above Code, in addition to using the event keyword, the event we define also uses a delegate type. However, if a delegate is a class, the class must have an attribute field, however, we canEventUnderstandingIs an attribute of the delegate, and the returned value of the attribute is a delegate type.It is said that an event is a delegate attribute and is justified. We can use the intermediate language code to know how the compiler interprets the events we define.

// Step 2: Define a birthday event. First, define a delegate type to specify the method type called when the event is triggered. Public Delegate void birthdayeventhandle (Object sender, birthdayeventargs E ); // define the birthday event public event birthdayeventhandle birthdayevent;

When we define an event like above, the compiler will convert it into three pieces of code (which can be viewed by the Il disassembly program ):

// 1. private birthdayeventhandle birthdayevent = NULL; // 2. A public add_birthdayevent method public void add_birthdayevent (birthdayeventhandle value) {// Add a delegate from the event in a thread-safe way} // 3. A public remove_birthdayevent method public void remove_birthdayevent (birthdayeventhandle value) {// remove a delegate from the event in a thread-safe way}

The first code is a private field of the Delegate. This field is a reference to the header of a delegate list. when an event occurs, the delegate in this list is notified. The field is initialized to null, indicating that the event is followed by no followers.
The second code is a method prefixed with "add", which is automatically named by the compiler and called by the Code content.Delegate. CombineMethod to add the delegated instance to the delegate list, return to the new list address, and save this address back to the field.

The third code is also a method, which causes an object to log out of the event's concern. The same method body calls delegate. the Remove Method deletes the delegated instance from the delegate list, returns the new list address, and saves the address back to the field. (Note: If you try to delete a method that has never been added,Delegate. RemoveThe method does not do anything in the internal part. That is to say, it does not throw any time or display any warning, and the set of event methods remains unchanged ).

At the same time, you can also verify that the event is a delegated chain through debugging.Eventsource. birthdayevent + = new birthdayeventhandle (obj2.buycake); this line of code sets a breakpoint for debugging. below is one of my Debugging Processes. You can also debug it by yourself, in this way, we will better understand that an event is a delegated chain concept:

Press F10 to run

Through the above, I believe that you will have a better understanding of the concept that an event is a delegated chain.

Iv. Summary

The content of this topic is also described here. We hope that through this topic, you can have a further understanding of the incident and understand the relationship between the incident and the delegation. This topic explains the nature of an event through an event model implemented by itself. However, we often use events defined in the net class library, however, some people who are new to C # do not understand what is done behind the events defined in net. They just know how to click a button and write some of their own control code in the click method, however, what is the process behind it? Since the event is a delegate, the click event is a delegate type, and how is the delegate type instantiated? These contents will be shared with you in the next topic.

 

 

 

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.