将事件处理程序作为参数传递

use*_*403 4 c# events

好吧,我真的不知道我的代码有什么问题,以及发生了什么

class Activity 有以下方法

protected struct EventParams
    {
        public object sender;
        public EventArgs e;
    }
private EventParams WaitEventRaise_Body(ref EventHandler<EventArgs> handler, int timeout)
    {
        AutoResetEvent receiver = new AutoResetEvent(false);
        EventParams result = new EventParams();

        EventHandler<EventArgs> handle = new EventHandler<EventArgs>((sender, e) =>
        {
            result.e = e;
            result.sender = sender;
            receiver.Set();
        });

        handler += handle;

        if (timeout > 0)
        {
            receiver.WaitOne(timeout);
        }
        else
        {
            receiver.WaitOne();
        }

        return result;
    }

protected EventParams WaitEventRaise(ref EventHandler<EventArgs> handler)
{
    return WaitEventRaise_Body(ref handler, -1);
}
protected EventParams WaitEventRaise(ref EventHandler<EventArgs> handler, int timeout)
{
    return WaitEventRaise_Body(ref handler, timeout);
}
Run Code Online (Sandbox Code Playgroud)

好的,所以我发现自己一遍又一遍地写了AutoResetEvent,所以我决定创建一个方法.但是当我尝试从派生类调用此方法时Bot : Activity

EventParams eventResult = WaitEventRaise(ref currentJob.JobReported);
Run Code Online (Sandbox Code Playgroud)

错误30 Project.Activity.WaitEventRaise(ref System.EventHandler)'的最佳重载方法匹配包含一些无效参数

currentJob是一个Job : Activity有事件的类

public event EventHandler<JobReport> JobReported;
Run Code Online (Sandbox Code Playgroud)

class JobReport : EventArgs
Run Code Online (Sandbox Code Playgroud)

我想要做的是有一个机器人的东西做工作,实际上它创造了工作,并等待他们完成他们的工作.Job类在内部引发事件,使bot类注意到它完成了它的工作.机器人类等到工作提出事件.所以我希望它清楚.我很抱歉英语不是我的母语.

Jon*_*eet 7

基本上,你不能参考这样的事件.两种选择:

  • 传入代理"添加处理程序"和"删除处理程序":

    EventParams eventResult = 
        WaitEventRaise<JobReport>(handler => currentJob.JobReported += handler,
                                  handler => currentJob.JobReported -= handler);
    
    Run Code Online (Sandbox Code Playgroud)

    其中,WaitEventRaise将被宣布为:

    EventParams WaitEventRaise<T>(Action<EventHandler<T>> add,
                                  Action<EventHandler<T>> remove)
                                 where T : EventArgs
    
    Run Code Online (Sandbox Code Playgroud)
  • 传递EventInfo相应的事件,您可以使用反射获取该事件

这些都不是非常令人愉快 - 这也是Rx遇到的问题.