In system events, such as mouse clicks or keyboard buttons, the transmitter is the. NET Runtime Library.
Why do I need to use delegation? There is a method somewhere in the event receiver that handles the event. This event is executed every time a registered event occurs.Program. In this case, you need to use the delegate. Since the sender does not know anything about the receiver, it is impossible to set a reference type for both events. Instead, it uses the delegate as the intermediary.
Example to illustrate the problem:
Create a Windows form application program, add a buttonone button control and a labelinfo label control.
Add the following to the form1.cs file:Code:
Namespace windowsformsapplication1 {public partial class form1: FORM {public form1 () {initializecomponent (); buttonone. click + = new eventhandler (button_click); // This is equivalent to buttonone. click + = button_click. Tells the Runtime Library to execute the button_click method when a click event of buttonone is triggered. Eventhandler is the delegate used by the event to assign the handler (button_click) to the event (click. click + = new eventhandler (button_click); buttontwo. click + = new eventhandler (buttontwo_click); // defines the event. Clicking buttontwo not only changes the text, but also displays the message box. However, the label text cannot be changed before the message box is displayed.} private void button_click (Object sender, eventargs e) {If (button) sender ). name = "buttonone") {labelinfo. TEXT = "button one was pressed. ";} else {labelinfo. TEXT = "button two has pressed. ";}} private void buttontwo_click (Object sender, eventargs e) {MessageBox. show ("this only happens in button 2 Click Event ");}}}
The main learning point is that the event handler cannot return values. It is actually a parameter. If you use the eventhandler delegate, the parameters are object and eventargs. The Lambda expression is like this.
Buttonone. click + = (sender, e) => labelinfo. TEXT = "button one was pressed"; buttontwo. click + = (sender, e) => labelinfo. TEXT = "button two was pressed"; buttontwo. click + = (sender, e) => {MessageBox. show ("this only happens in button 2 Click Event ");}