Create a new winform application. Drag a button in Form1 and double-Click it to generate a Click event. Add this code to the event.
MessageBox. Show ("hello ");
F5 debugging run. Event demo OK
Next we will discuss this "Event" in Form1.cs node open Form1.Designer. cs, expand "Windows Forms designer generate code node", find
This. button1.Click + = new System. EventHandler (this. button#click );
In a simple analysis, add an EventHandler event processing mechanism to the Click Event of the button1 button in this form. The handler is the method button#click.
Click F12 at EventHandler To Go To The definition and find that EventHandler is actually a delegate.
Public delegate void EventHandler (object sender, EventArgs e );
Then we will rewrite his code based on the nature of his delegate: the rewrite is as follows: this. button1.Click + = this. button#click; Let's click F5. The code runs normally. It can be abbreviated. This is what we expected.
To put it simply, Delegate,
Public delegate void EventHandler (object sender, EventArgs e );
The delegate is the modifier of the delegate, the public modifier is the public, and the void is the return value. It looks like a method, but the delegate is not equivalent to a method, but a reference type. is the security pointer in C.
The method associated with the delegate must have the same return value type and parameter list as it does. Let's take a look at the button#click method generated by double-clicking, right? This is critical.
Now, modify the Cilk event and declare an anonymous delegate after + =. The Code is as follows:
This. button1.Click + = delegate (object sender, EventArgs e)
{MessageBox. Show ("hello ");};
(Here EventArgs and MessageBox need Ctrl +. PARSE)
OK. In this way, we can delete the button#click method in Form1.cs, which has been abandoned by us. run F5 to verify your program. run OK to continue the following modifications (prerequisite. net3.5 and later versions), the Code is as follows:
This. button1.Click + = (sender, e) => MessageBox. Show ("hello ");
Run through.
Delegate, anonymous method, and Lambda expression.