First of all, the use of events in C #, from the use of events, I myself will produce a doubt
C # Events
classProgram {Static voidMain (string[] args) {EventClass EC=NewEventClass (); EC.HD+=Neweventclass.handledelegate (EC_HD); stringstr = EC. OnClick ("aaaaaaaaaaaaaaa");//My confusion appears here Console.WriteLine (str); Console.readkey (); } Public Static stringEC_HD (stringstr) { returnstr; } } classEventClass { Public Delegate stringHandledelegate (stringstr); Public EventHandledelegate HD; Public stringOnClick (stringstr) { returnHD (str); } }}
Previously, the button object added an event, namely btn. Click+=button1_click; So it's done, but I don't understand who called this delegate, that is, "string str = EC," as in the above code. OnClick ("aaaaaaaaaaaaaaa");//My confusion appears here "in this line."
Through the Anti-compilation tool, know how this is called, the Anti-compilation button class can be seen, the following brief description:
The following code is added to execute the Click event:
// Events [Webcategory ("Action"), Websysdescription ("button_onclick" )] publicevent EventHandler Click { add { base. Events.addhandler (Eventclick, value); } Remove { base. Events.removehandler (Eventclick, value); } }
This code is the code of the + = Operation call, and the Click event is added to the events collection
About the events collection, which is a property, it returns an events object, the Events object is of type EventHandlerList, the key of the collection is of type object, and the value is, of course, eventhandle.
Then the code for the doubts is as follows:
protected Virtual void OnClick (EventArgs e) { // in the Events collection, return the Click event Object, and then call the Base . Events[eventclick]; if NULL { handler (this, e);//This Code is like the EC in the first code . OnClick ("aaaaaaaaaaaaaaa");
}
As for how the OnClick method is invoked, it involves deeper operations, such as how a button is clicked, which is not necessary to understand.
This article is just to solve some of my doubts.
But it also gives the code to invoke the onclick:
protected Virtual voidRaisePostBackEvent (stringeventargument) { Base. Validateevent ( This. UniqueID, eventargument); if( This. CausesValidation) { This. Page.validate ( This. ValidationGroup); } This. OnClick (Eventargs.empty); This. OnCommand (NewCommandEventArgs ( This. CommandName, This. CommandArgument)); }
Solve your own doubts about the Click event of C # button