C # Basic Series-No more worrying about the interviewer asking me "events".

Source: Internet
Author: User

Preface: As. NET siege Lion, have you ever encountered such a problem during the interview process: What is an event? What is the difference between an event and a delegate? Since the event is a special delegate, how does its advantage manifest itself? Such... Have you ever been asked? Have you ever answered it? In two articles, the use of the following delegate is introduced by shallow and deep, this article is to say the incident. Hope that through this introduction, Bo friends can have a system of understanding, at least to deal with the interview no problem. Don't believe me? Look at that.

C # Basic Series Catalog:

    • C # Basic Series--LINQ to XML read and write XML
    • C # Basic Series-The use of extension methods
    • C # Basic Series--Serialization efficiency competition
    • C # Basic Series-Reflection notes
    • C # Basic Series--attribute features use
    • C # Basic Series--small-talk generics
    • C # Basic Series--an explanation of common usage of multithreading
    • C # Basic Series--delegation and design pattern (i)
    • C # Basic Series--delegation and Design pattern (ii)

The beginning Bo Master also not much nonsense, Cui flower, on the answer ... We just need to grab a few key points about the events involved in the interview:

(1) The event is the encapsulation of a delegate, which can be understood as a special delegate.

(2) In fact, there are two methods in the event (i.e. add_event () and Remove_event ()) and a private delegate variable, which is the merging and removing of the private delegate variable, which is actually a call event when the + = of the event is called add_ The event () method, the same-= call is the Remove_event () method.

(3) The event can only add new response methods from outside the object and delete the known response method, but not the initiative to trigger the event and get other registered response methods and other information. These restrictions cannot be made if the public delegate are used, which means that the event restricts the delegate and makes the delegate more convenient to use. It is also said that the event is a commission of castration, probably also this meaning.

If you catch the above 3 points in the answer, then I think your interview should not be too bad. After all, the interview so short of time, there are one or two highlights is very good, you say. Even if you do not understand the mechanism of the event, in order to remember two of the interview is also very good, work experience we do not, change the experience of the work can not be no Oh ~ ~ Pull away, about the interview so far. If you still want to keep the story in perspective, don't worry, look down.

1, the definition and origin of the event:

To define an event:

     Public Delegate void Mystudyevent (object  sender, EventArgs e);      Public class testevent    {        publicevent  mystudyevent emystudyevent;    }

After the code has been generated by the DLL, the reflector can be seen by the anti-compilation tool:

As mentioned above, you can see that when you define a public event mystudyevent emystudyevent, the compiler automatically generates two methods for him, add and remove, and a private delegate variable, emystudyevent. We will copy the anti-compilation code to see.

//Private Delegate Variable        Privatemystudyevent emystudyevent; //Add method Merge delegate to emystudyevent inside         Public voidadd_emystudyevent (mystudyevent value) {mystudyevent event3; Mystudyevent emystudyevent= This. emystudyevent;  Do{Event3=emystudyevent; Mystudyevent Event4=(mystudyevent) System.Delegate.Combine (event3, value); Emystudyevent= Interlocked.compareexchange<mystudyevent> (ref  This. Emystudyevent, Event4, Event3); }             while(Emystudyevent! =Event3); }        //The Remove method removes the existing delegate from the Emystudyevent         Public voidremove_emystudyevent (mystudyevent value) {mystudyevent event3; Mystudyevent emystudyevent= This. emystudyevent;  Do{Event3=emystudyevent; Mystudyevent Event4=(mystudyevent) System.Delegate.Remove (event3, value); Emystudyevent= Interlocked.compareexchange<mystudyevent> (ref  This. Emystudyevent, Event4, Event3); }             while(Emystudyevent! =Event3); }

As you can see, the main function of these two methods is to add delegates and remove delegates to the private variable emystudyevent. When the event is called + = and-=, the emystudyevent inside merges and removes the passed-in delegate, and when the event is triggered, the emystudyevent variable executes. This design also coincides with the principle of encapsulation, ensuring the security of internal variables.

2, the framework of the event: Since the custom event is this, then someone will ask,. NET is the same thing. We look directly at the Anti-compilation tool. We found the button class below System.Windows.Forms, which is also the most used buttons in our WinForm, let's take a look at the events we use frequently.

Base. DoubleClick go To Definition:

Events.addhandler () go To Definition:

is not very familiar, but also through the delegate.combine () to consolidate the delegation.

3, the use of custom events. Examples of events used in the garden is also a lot of articles, this film blogger to listen to the folder 1.txt files exist as an example of the use of events and the use of events and delegate differences.

First define the event and the method that triggered the event:

  

Public Delegate voidFilewatcheventhandler (Objectsender, EventArgs e); Public classFilewatch {Private BOOL_blaststatus =false; PublicFilewatch () {} Public EventFilewatcheventhandler filewatchevent; protected Virtual voidOnfilechange (EventArgs e) {if(Filewatchevent! =NULL) {filewatchevent ( This, E); } }
How to listen for events Public voidMonitorfile () {BOOLBcurrentstatus; while(true) {Bcurrentstatus= File.exists (@"C:\Users\user\Desktop\ Desktop Folder \1.txt"); if(Bcurrentstatus! =_blaststatus) {_blaststatus=Bcurrentstatus; Onfilechange (Eventargs.empty); } thread.sleep ( -); } } }

Then start the listener in the main function and define the event handling method:

StaticFilewatch Filewatcheventsource; Static voidMain (string[] args) {Filewatcheventsource=NewFilewatch (); //1. Start a background thread to add a monitoring event            varTHRD =NewThread (NewThreadStart (filewatcheventsource.monitorfile)); Thrd. IsBackground=true; Thrd.            Start (); //2. Registering local event handling methodsfilewatcheventsource.filewatchevent+=NewFilewatcheventhandler (Onfilechange);        Console.ReadLine (); }        Private Static voidOnfilechange (ObjectSender, EventArgs e) {Console.WriteLine (DateTime.Now.ToString ()+": The file has changed."); }

When you start the program, you will be prompted to change the file whenever you delete and create 1.txt in the folder.

Bo main curiosity, it seems that this kind of monitoring directly with the delegation can also be achieved. The event variable is then changed directly to the delegate variable.

// Public event Filewatcheventhandler Filewatchevent;  Public Filewatcheventhandler filewatchevent;

and then run. Find that you can get the same results.

There is no add and remove methods at the time of Anti-compilation:

Here is the need to explain the above interview answer third: The event can only be castrated through + = and-+ to castrate the delegate, but not the initiative to trigger the event. such as when using the mechanism of the event public event Filewatcheventhandler Filewatchevent. Inside the main function

Static voidMain (string[] args) {Filewatcheventsource=NewFilewatch (); //1. Start a background thread to add a monitoring event            varTHRD =NewThread (NewThreadStart (filewatcheventsource.monitorfile)); Thrd. IsBackground=true; Thrd.            Start (); //2. Registering local event handling methodsfilewatcheventsource.filewatchevent+=NewFilewatcheventhandler (Onfilechange);            This is an error in writing. Filewatcheventsource.filewatchevent (NULL,NULL);        Console.ReadLine (); }

This is an error filewatcheventsource.filewatchevent (null, NULL), because the event cannot be actively triggered, and it is correct to write the delegate after it has been changed. And if it is an event variable, all other operations, except the + = and-= operations, will be error:

As you can see from here, the event encapsulates and constrains the delegate.

In a word, in short, events and commissions, a less appropriate analogy, like bread and flour, bread is processed from flour, when we are hungry, bread can eat directly, flour also needs processing. And when we need noodles, flour comes in handy, and bread is not for us. I do not know how to explain it well. Said so much, indeed a bit around, need to have a good experience.

C # Basic Series-No more worrying about the interviewer asking me "events".

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.