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:
<code class="language-csharp">private void setup(string someData) { Object.assignHandler(evHandler); }</code>
And the event handler evHandler
needs to access the someData
parameter:
<code class="language-csharp">public void evHandler(Object sender) { // 需要在此处使用 someData!!! }</code>
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:
<code class="language-csharp">private void setup(string someData) { Object.assignHandler((sender) => evHandler(sender, someData)); }</code>
Now, the evHandler
method can accept both the sender and the someData
parameters:
<code class="language-csharp">public void evHandler(Object sender, string someData) { // 访问发送者和 someData }</code>
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!