Access extra parameters in event handler
Suppose you need to pass additional data to the event handler. For example, we have a setup method that assigns event handlers:
private void setup(string someData) { Object.assignHandler(evHandler); }
And the event handler evHandler
needs to access the someData
parameter:
public void evHandler(Object sender) { // 需要在此处使用 someData!!! }
Solution
To pass additional parameters to an event handler, you can use a lambda expression as a delegate. Instead of assigning the evHandler
method directly, we assign a lambda expression that takes the sender object as the first argument and someData
as the second argument:
private void setup(string someData) { Object.assignHandler((sender) => evHandler(sender, someData)); }
Now, the evHandler
method can accept both the sender and the someData
parameters:
public void evHandler(Object sender, string someData) { // 访问发送者和 someData }
The above is the detailed content of How Can I Pass Extra Parameters to Event Handlers in C#?. For more information, please follow other related articles on the PHP Chinese website!