How to attach EventArgs / user parameters when you assign a delegate to an event?

I have this code:

this.form.Resize += new EventHandler(form_Resize);

But I want to assign some objects for later access in the event form_Resize, how can I do this?

and access data in EventArgs?

+3
source share
3 answers

You cannot “assign additional data” to a delegate, but you can create a parameterized version of the method form_Resizeand then use lambda expressions (in C # 3+) or anonymous delegates (C # 2+) to specify additional data when connecting a handler. One way to write this:

void form_Resize(object sender, EventArgs e, Data additional) {
  // 'additional' contains whatever you specified when attaching handler
}

this.form.Resize += (s, e) => form_Resize(s, e, yourAdditionalData);
+7
source

. , .

0

It depends on what exactly you mean. EventHandler is a predefined delegate type, so two parameters (sender and EventArgs) will be automatically passed in the form_Resize method. On the other hand, you can access all the fields of the class where the form_Resize method is determined from the form_Resize method itself.

You can learn more about the EventHandler delegate here.

0
source

Source: https://habr.com/ru/post/1732765/


All Articles