Events are an important part of C #. There is a demo of custom events on msdn. After reading it for a long time, I was a little dizzy. So I created a new winform project and added a button to find the program to be called. I made a similar one-to-one comparison example and I understood it. Reading code is sometimes faster than reading a document.
Therefore, it is a consistent principle.
Using system; namespace testeventargs {// <summary> // This class corresponds to eventargs for comparison and learning. /// Add info1 and info2. /// </Summary> public class myeventargs: eventargs {private string info1; private uint32 info2; Public myeventargs (string info1, uint32 info2) {This. info1 = info1; this. info2 = info2;} Public String info1 {get {return this. info1;} set {This. info1 = value ;}} public uint32 info2 {get {return this. info2;} set {This. info2 = value ;}}/// <summary> // simulate the button /// </Summary> public class mybutton {Public Delegate void myevnethandler (Object sender, myeventargs E); // <summary> // counter of the number of times the button is clicked /// </Summary> Public static uint32 clicked_num = 0; public event myevnethandler myclick; public void trigger () {myeventargs Arg = new myeventargs (datetime. utcnow. tostring (), ++ clicked_num); myclick (this, ARG );}} /// <summary> /// simulate form /// </Summary> public class myform {public mybutton; Public myform () {button = new mybutton (); button. myclick + = new mybutton. myevnethandler (this. button_clicked);} public void button_clicked (Object sender, myeventargs e) {console. writeline ("button clicked (sender is:" + sender. tostring () + "; info1 =" + E. info1 + "; info2 =" + E. info2) ;}} class program {static void main (string [] ARGs) {myform form = new myform (); For (INT I = 0; I <10; I ++) {form. button. trigger (); system. threading. thread. sleep (500);} console. writeline ("press any key to continue... "); console. readkey ();}}}
Different Places:
1 in this example, delegate myevnethandler is a member of the mybutton class. In the system, eventhander is a member of the system namespace.