【. NET Foundation "--delegates, events, Threads (2)

Source: Internet
Author: User

This article describes the use of the event and the principle of this article after the demo of an article continue to "Download the previous demo"

In the previous article, we defined 4 delegate in the Class (Dg_sayhi.cs) , then created the delegate object in the background event of the button and initialized it to use the delegate. In this article we look at the use and rationale of the event.

1, now we define a DG_SAYHI delegate variable inside the person class so that the new person class object can manipulate the delegate variable

A,person class Add Delegate variable

  Public classPerson {#regionNamestringname;  Public stringName {Get{returnname;} Set{name =value;} }        #endregion        #regionAgeintAge ;  Public intAge {Get{returnAge ;} Set{age =value;} }        #endregion        //Defining delegate Variables         PublicDg_sayhi Dgsayhi; }
View Code

B, add button Btnperson and Btnpersondelegate_click event, we use delegate object in event

  Private void Btnpersondelegate_click (object  sender, EventArgs e)        {            new  Person ();             // Dgsayhi object that creates a delegate object and assigns a value to the person object            New Dg_sayhi (SAYHICN);             + = Sayhien            ; // invoking a Delegate object             Per.dgsayhi ();        }

C, so click on the button, call Sayhicn and Sayhien method, respectively, pop-up window "Hello Shanghai" and "Hi Shanghai".

D, because it is the direct operation of the delegate object Dgsayhi, so that you can directly add the method of the delegate object to empty or reset, we update the button background event as follows:

     Private voidBtnpersondelegate_click (Objectsender, EventArgs e) {person per=NewPerson (); //Dgsayhi object that creates a delegate object and assigns a value to the person objectPer.dgsayhi =NewDg_sayhi (SAYHICN); Per.dgsayhi+=Sayhien; //The following code clears the method previously added to the delegate and resets the delegate object to thePer.dgsayhi =NULL; Per.dgsayhi=NewDg_sayhi (Sayhien); //invoking a Delegate objectPer.dgsayhi (); }
View Code

E, the above, the delegate object in the process of operation will be unreasonable emptied out, this is not safe.

2, in order to restrict the operation of the delegate object, we define the delegate object as private and then add the method of manipulating the delegate object like the property.

A, update the person class, turn the delegate into private, and add a method to manipulate the private variable

   Public classPerson {#regionNamestringname;  Public stringName {Get{returnname;} Set{name =value;} }        #endregion        #regionAgeintAge ;  Public intAge {Get{returnAge ;} Set{age =value;} }        #endregion        #regionImplementing the protection of delegate variables//Defining delegate Variables        PrivateDg_sayhi Dgsayhi;  Public voidAddmethod (Dg_sayhi para_dgsayhi) {Dgsayhi+=Para_dgsayhi; }         Public voidRemovemethod (Dg_sayhi para_dgsayhi) {Dgsayhi-=Para_dgsayhi; }         Public voidPrintmethod () {dgsayhi (); }        #endregion    }
View Code

B, so that we can not directly manipulate the delegate object, only with the help of a similar property two methods to add to the delegate object, remove the method, update the button event as follows:

     Private void Btnpersondelegate_click (object  sender, EventArgs e)        {            new  Person ();            Per. Addmethod (SAYHICN);            Per. Addmethod (Sayhien);            Per. Printmethod ();        }

C, the above so that we can not directly manipulate the delegate object, thus realizing the protection of the delegate object.

3, in fact, the. NET event helps us to do the same as the Step 2 package, so as to achieve the protection of the delegate object

A, the delegate for which we add the event declaration again in the person class is as follows:

     // define events to implement the same functionality        as the packages above  Public Event dg_sayhi dgsayhibyevent;          Public void printmethodevent ()        {            dgsayhibyevent ();        }

B,button background events, we can only add the removal method to the delegate object, but not to empty or new, as follows:

      Private voidBtnpersondelegate_click (Objectsender, EventArgs e) {person per=NewPerson (); ////Create a Delegate object and assign a value to the Dgsayhi object of the person object            //per.dgsayhi = new Dg_sayhi (SAYHICN); //Per.dgsayhi + = Sayhien;            ////The following code clears the method previously added to the delegate and resets the delegate object to the            //per.dgsayhi = null; //per.dgsayhi = new Dg_sayhi (Sayhien);per.dgsayhibyevent+ = SAYHICN;//The event implements the protection of the delegate object, which can be + =, =, but can no longer be initialized or emptied as abovePer.dgsayhibyevent + =Sayhien; //It is not possible to invoke the delegate object directly, but through the method call of the object; It is not possible to write: Per.dgsayhibyevent ();per.        Printmethodevent (); }

C,.net Reflector We look at this, we add the delegate to the event, which is actually 1, created the private Dgsayhibyevent delegate object 2, and added two methods to the event events: Add and Remove methods These two methods are used to manipulate the private Dgsayhibyevent delegate object. (similar to Set,get)

  

D, the essence of the event keyword is to do two things to protect the delegate object:

1, a corresponding private delegate object is created

2, then add and remove methods to access, manipulate the private delegate object.

  

4, Comparison of delegates and events:

A, the delegate is a class, only define the delegate object, can not achieve the protection of the delegate object, the external may be emptied and new

B, the event is a delegate object, the event itself implements the protection of the delegate object, and provides two methods for external access

C, events can only be add,remove to themselves, and cannot be assigned values. Events can only " register themselves + = ", " write-off yourself =" cannot =, the outside world can not write off other registrants, the outside world can not actively trigger events.

"This demo download"

【. NET Foundation "--delegates, events, Threads (2)

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.