C # event triggering mechanism

Source: Internet
Author: User

C # event triggering mechanism, similar to C + + callback function mechanism

Let me say briefly, the nature of the Commission and the event, and then re-open a blog in detail.

Delegate: A pointer to a method, a function pointer similar to C

Event: is a data structure that can hold 0 or more method pointers .... A class is generated for it after a compilation, and so on, and so on, and then another blog post.

Look at the trigger mechanism.

easy to understand, to a popular figure

Event Trigger Source Class

    classCclass {Private Chari;  Public Delegate voidichanged (Cclass s);  Public Eventichanged value_changed; protected Virtual voidOnValueChanged (Cclass message_str)//triggering an event in the Onxxxxxx method{ichanged temp_value_changed= Volatile.read (refvalue_changed);//Keep thread safe, keep a backup            if(Temp_value_changed! =NULL) {temp_value_changed (MESSAGE_STR); }        }         Public CharI {Get            {                returni; }            Set            {                if(value!=i) {i=value;  This. onvaluechanged ( This);//Call the Onxxxxxxx method when the value is modified                }            }        }    }

Registering a method for an event in another class, triggering an event when modifying a value, executing a method

 classProgram {Static voidMain (string[] args) {Cclass C=NewCclass (); C.value_changed+=c_value_changed;//Register the method on the event,            Chari =Console.readkey ().            KeyChar;  while(i!= -)//Enter Exit{Console.WriteLine (); C.I.= i;//values are modified, events are triggered, and all methods registered to the event are executedi =Console.readkey ().            KeyChar; }        }        Private Static voidc_value_changed (Cclass s) {Console.WriteLine ("value is changed>>>>i:"+s.i); }    }

Effect

Source Connection: Http://pan.baidu.com/s/1i3UXHKp

C # event triggering mechanism

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.