In the past two days, I have reviewed my knowledge about delegation and events.
1. Delegate
Delegate is the ability to pass methods as variables.
The specific steps for using delegation in C # are as follows:
(1) Statement of delegation. The parameter format must be the same as the parameter format of the method to be included. The delegate can call different methods when the program runs, as long as the method signature is consistent with the delegate signature.
Format:
[Modifier] delegate number of type returned by delegate (parameter list)
For example:
MyDelegate1 (MyDelegate2 (); // No Parameter
Declaring a delegate object is the same as declaring a common class object.
MyClass1 cls = = = = MyDelegate2(cls.dMethod3);
Delegate name delegate object;
(2) define all methods to be defined. The parameter format must be the same as that of the delegate object declared in step 1.
Define the method of delegation:
DMethod1 (dMethod2 ((4) Call the methods contained in the delegate object
d1( dbTemp=d3();
Detailed instance:
DMethod1 (dMethod2 (MyDelegate1 (Main (=== MyDelegate1 d4 = d1 + dbTemp =MyEventHander active;+ = EventHandler (handler );
In the winform
OkButton.Click+= EventHandler(OkButton.Click);
Once an event is triggered, the predefined method is called.
Event Cancellation
Format:
Event name-= new delegate name (method name );
OkButton.Click-= EventHandler(OkButton.Click);
Only the + = and-= operators can be used for event operations.
(3) event occurrence
The event is the call of the delegate corresponding to the event, that is, the call of each method contained in the delegate call list.
Format:
Event name (parameter );
Detailed instance:
MyEventHandler (); MyEventHandler activate; Fire () (activate! = Main (= + = MyEventHandler (Handler); evt. Fire ();Main (= + = alarm. MakeAlarm; heater. Boiled + = (Alarm (). MakeAlarm; heater. Boiled + = Display. ShowMsg;Type = area = BoiledEventArgs (. temperature = (Boiled! =, E); (I =; I <=; I ++ = (temperature> ==ShowMsg (= sender