[C # Basic Knowledge Series] Topic IV: Event Disclosure

Source: Internet
Author: User

Transfer from http://www.cnblogs.com/zhili/archive/2012/10/27/Event.html

Introduction:

The first few topics on the delegation are described in detail, and then we often hear the concept of "events" in the process of writing code, especially when we write the UI, when we click on a button, VS will automatically help us generate some background code, and then we just need to write code in the click Method can be, So maybe some friends who have just come into contact with C # feel this way, and don't think about why, why the Click event will trigger the code we write in the click method? What kind of role does an event play? To lift these doubts, the following details the events, allowing some beginners to understand the concept of events in C # in depth.

First, why is there an event in C #?

The previous topic describes why I need to delegate, so here I share what I understand why C # introduces the concept of events. The following is a brief talk about the case of life events, recently my birthday just finished, I will be a birthday this topic to talk about, the days of the past, when the date of the birthday, this time triggered the birthday event, at this time the birthday of the person is the object of the event to trigger birthdays, And then some relationship your friends will pay attention to this event, once the event triggers, they may accompany you to celebrate the birthday, and then send you a gift, of course, not everyone will pay attention to your birthday, some people certainly do not know, only the person who has paid attention to your birthday event will send you a gift. A birthday process in this life, however, for why the concept of events in C # is better understood, C # is an object-oriented language, and we use the C # language to code to help us do real-life things, so of course there must be events To reflect what's going on in your life.

Ii. How do you implement an event pattern?

Now that we know why C # is introducing events, But for most of the events we use in our code are the. NET class libraries that provide us with events like controls, we just need to click the button to trigger the Click event, but we would like to understand how this event is triggered, can we define a program that implements the event pattern ourselves? The answer, of course, is yes, following the example of the above birthday to explain how to implement an event pattern through the code.

The specific code is:

Using system;using System.threading;namespace birthdayeventdemo{class Program {static void Main (string[] ar            GS) {//Instantiate an Event source object Me EventSource = new Me ("Learning hard");            Instantiate the object of interest Friend1 obj1 = new Friend1 ();            Friend2 obj2 = new Friend2 (); Use delegates to register objects and their methods in the event Eventsource.birthdayevent+=new Birthdayeventhandle (obj1.            Sendgift); Eventsource.birthdayevent+=new Birthdayeventhandle (obj2.                        Buycake);            Event to trigger Birthday event, event call Eventsource.timeup ();        Console.read ();        }}//First step: Define a type to hold all additional information that needs to be sent to the event recipient public class Birthdayeventargs:eventargs {//name of birthday person        Private readonly string name;        public string Name {get {return Name;}        } public Birthdayeventargs (string name) {this.name = name; }}//Second step: Define a Birthday event, first you need to define a delegate type that specifies the type of method to invoke when the event is triggered PubliC delegate void Birthdayeventhandle (object sender, Birthdayeventargs e);        Define event members public class Subject {//define Birthday Events public event Birthdayeventhandle Birthdayevent; Step three: Define a method that is responsible for raising an event that notifies the object of interest (notifies my friends) protected virtual void Notify (Birthdayeventargs e) {//out of For thread safety, now copy the reference to the delegate field into a temporary field birthdayeventhandle temp = Interlocked.compareexchange (ref birthdayevent, NULL, n            ULL); if (temp! = null) {//trigger event, same as method used//Event notification delegate object, delegate object call encapsulated method tem            P (this, e);        }}}//Define the object that triggered the event, event source public class Me:subject {private string name;        Public Me (string name) {this.name = name;            } public void Timeup () {Birthdayeventargs EventArg = new Birthdayeventargs (name); The birthday is up, inform the friends this.        Notify (EventArg);       }}//Friend object public class Friend1 { public void Sendgift (Object Sender,birthdayeventargs e) {Console.WriteLine (e.name+ "Birthday is coming, I want to send a gift");            }} public class Friend2 {public void Buycake (object sender, Birthdayeventargs e) {        Console.WriteLine (e.name + "Birthday is coming, I'm going to buy a cake"); }    }}

The result of the operation is:

Third, how does the compiler interpret the event?

Above we have introduced how to implement an event pattern, you can expand the code to see the specific, the implementation process is mainly-define the event source to trigger the object (refers to the birthday), and define the friend object that concerns your birthdays. Method register concerns about the event, Notifies the enlisted method when the event is triggered. But I believe there are questions-what is the event in C #? How does the compiler explain it? Here are the questions for everyone to be relieved:

The first event is actually the delegate (the exact event is the delegate chain ), from the above code, we define an event in addition to using the event keyword, but also the use of a delegate type, but the delegate is a class, The class must have an attribute field, but we can interpret the event as a property of the delegate, and the return value of the property is a delegate type. to say that an event is a property of a delegate, is based on that we can know through the intermediate language code how the compiler interprets the events we define.

Second step: Defining a Birthday event, you first need to define a delegate type that specifies the method type that is called when the event is fired public    delegate void Birthdayeventhandle (object sender, Birthdayeventargs e);    Define Birthday Events Public        event Birthdayeventhandle Birthdayevent;

When we define an event like above, the compiler converts it to 3 pieces of code (which you can see through the Il disassembler):

     1. A private delegate field that is initialized to null private       birthdayeventhandle birthdayevent =null;        2. A common add_birthdayevent method public        void Add_birthdayevent (birthdayeventhandle value)        {            // Add a delegate from an event in a thread-safe way        }        //3. A common Remove_birthdayevent method public        void Remove_birthdayevent ( Birthdayeventhandle value)        {            //Remove a delegate from an event in a thread-safe way        }

The first paragraph of code is a delegate's private field, which is a reference to the head of a list of delegates, which notifies the delegate in the list when the event occurs. The field is initialized to NULL, indicating that no concern has been registered to concern the event.
The second code is a method prefixed with add, which is automatically named by the compiler, which calls the Delegate.combine method to add the delegate instance to the list of delegates, returns the new list address, and saves the address back to the field.

The third code is also a method, which causes an object to unregister the attention of the event, the same method body calls the Delegate.remove method to remove the delegate instance from the delegate list, return the new list address, and store the address back in the field. (Note that if you attempt to delete a method that has never been added, thedelegate.remove method will not do anything internally, that is, it will not throw any time, nor will it show any warnings, and the collection of methods for the event remains the same).

At the same time you can also debug to show that the event is a delegation chain, you can eventsource.birthdayevent+=new birthdayeventhandle (obj2. Buycake); This line of code set a breakpoint debugging, the following is one of my debugging process, you can also debug their own to see, so that will be more understanding of the concept of the event is a chain of trust:

After you press F10 to run a line

Through the above, I believe you will have a further understanding of the concept of an event as a chain of trust.

Iv. Summary

Here the content of this topic is also introduced, hope that through this topic, you can have a further understanding of the incident, understanding the relationship between the event and the delegation. This topic explains the nature of events through an event pattern that we implement, but we often use events that are defined in the Net class library, but some people who are just in touch with C # do not understand what is going on behind the events defined in net. Just know the button after the click to write some of their own control code, but the process behind the specific how, since the event is a delegate, then the Click event is a delegate type, where the delegate type and how is it instantiated? The content will be shared with you in the next topic.

[C # Basic Knowledge Series] Topic IV: Event Disclosure

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.