Home >Backend Development >C++ >How Can I Pass Extra Parameters to Event Handlers in C#?

How Can I Pass Extra Parameters to Event Handlers in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-23 08:16:09374browse

How Can I Pass Extra Parameters to Event Handlers in C#?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn