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
Release: 2025-01-23 08:16:09
Original
344 people have browsed it

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>
Copy after login

And the event handler evHandler needs to access the someData parameter:

<code class="language-csharp">public void evHandler(Object sender)
{
    // 需要在此处使用 someData!!!
}</code>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template