将参数传递给 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将参数传递给 EventHandler

基础教程推荐