将参数传递给 EventHandler

Pass parameter to EventHandler(将参数传递给 EventHandler)
本文介绍了将参数传递给 EventHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 EventHandler 我添加了参数 MusicNote 音乐:

I have the following EventHandler to which I added a parameter MusicNote music:

public void PlayMusicEvent(object sender, EventArgs e,MusicNote music)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

我需要像这样将处理程序添加到 Timer:

I need to add the handler to a Timer like so:

myTimer.Elapsed += new ElapsedEventHandler(PlayMusicEvent(this, e, musicNote));

但得到错误:

需要方法名"

在这种情况下,我只是从包含此代码片段的方法中传递 e,我将如何传递计时器自己的 EventArgs?

In this case I just pass e from the method which contains this code snippet, how would I pass the timer's own EventArgs?

推荐答案

Timer.Elapsed 需要特定签名的方法(带有参数 objectEventArgs).如果您想使用 PlayMusicEvent 方法并在事件注册期间评估附加参数,则可以使用 lambda 表达式作为适配器:

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

您也可以使用较短的版本:

you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

这篇关于将参数传递给 EventHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)