Pass parameter to 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
需要特定签名的方法(带有参数 object
和 EventArgs代码>).如果您想使用
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将参数传递给 EventHandler


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01