C # Events

Source: Internet
Author: User

First, preface: The previous essay said the commission, now look at what the event can do, in the previous essay, the use of the process of delegation, there is a very awkward, but also very obvious problem, that is, the first time the delegation must initialize with "=", binding two times the event with "+ =" This is very, What's the point? Fortunately, the event is to solve the problem (without initialization, direct use of "+ ="), of course, the delegation encapsulated into an instance of the Sayhellomanager class can also solve the problem, the specific practice of referring to the previous essay;

Ii. Overview

1, Event: The event from a code point of view, is the declaration of a delegate type of variable, the implementation code is as follows:

usingSystem;namespaceevent{ Public Delegate voidMyEventHandler (string_name); classevent1{Static voidMain (string[] args) {Bulidsoftmanager BSM=NewBulidsoftmanager (); Bsm.myevent= BULIDBYC;//Compile Error Details: Event.BulidSoftManager.myevent can only appear to the left of + = or-= (except for use in Event.bulidsoftmanager)bsm.myevent+=Bulidbycsharp; Bsm. Bulidsoftwalk ("OA", bsm.myevent);//on the same       }       Static voidBULIDBYC (string_softname) {Console.WriteLine (_softname+"This software is written by C."); }       Static voidBulidbycsharp (string_softname) {Console.WriteLine (_softname+"This software is written in C #"); }    }     Public classbulidsoftmanager{ Public EventMyEventHandler MyEvent;  Public voidBulidsoftwalk (string_softname,myeventhandler Bulid)         {bulid (_softname); }    }}

Analysis: More with the above error hint, this time to use the Anti-compilation tool Reflactor to see the MyEvent event inside the structure;

Above is the basic structure of myevent, consisting of two methods with no return value (Add_myevent and Remove_myevent) and a myevent attribute. Then click on the MyEvent property to discover

Suddenly, the MyEvent event was compiled into the private delegate variable of the MyEventHandler delegate, so no matter what modifier you add to the event, he will be compiled into the private delegate variable of the target delegate.

The following is the structure of the remaining two methods, posted to look at:

Well, according to the above diagram and inference, it is generally known that the internal approximate operating mechanism of the event

<1>myevent is indeed a delegate of the MyEventHandler type, except that whatever modifier is added to MyEvent, he is private because it is forced to be compiled into private by the compiler,

The Add_myevent () and remove_myevent correspond to the "+ =" and "-=" operations, which are used to register the delegate type's method and unregister, and the access restrictions for both methods depend on whether the event you define is exposed externally.

If you define an event that is private, you cannot invoke the event in an external class, and of course you cannot use both methods.

<2>add_myevent () Method overview

As you can see, inside the Add_myevent () method, you actually call the System.Delegate combine () static method, which is used to add the current variable to the delegate list. We mentioned two times before that the delegate is actually a class;

2, to sum up: Draw such a few conclusions

After the <1> event is defined, it is compiled by the compiler into a variable of the delegate type, which is private to the class that defines (encapsulates) the event , which cannot be assigned when the external class uses the event (that is, "="), but can be used in the class that defines the event;

<2> events can be "+ =" and "-=" in cases where the event allows access, for reasons explained above;

Third, examples

It is now necessary to design an automotive fuel monitoring system when the oil content is less than 10 liters:

1, car alarm alarm-drip sound

2, the instrument panel display the corresponding warning message

usingSystem;namespaceevent{classevent1{Static voidMain (string[] args) {Car Car=NewCar ();        Car.drive (); }   }   //define the required fields for a car class, package oil volume, temperature, etc.    Public classcar{ Public int_oilmass;  Public intoilmass{Get{return_oilmass;} Set{_oilmass=value;} }           Public voidDrive () {if(oilmass<=Ten) {makealarm (oilmass);                    ShowMsg (Oilmass); }          }           Public voidMakealarm (int_oilmass) {Console.Write ("Insufficient oil content {0}l, please refuel in time", _oilmass); }           Public voidShowMsg (int_oilmass) {Console.Write ("Insufficient oil content {0}l", _oilmass); }   }}

C # 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.