gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:41:57 27 4
gpt4 key购买 nike

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

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);
}

好吧,我发现自己一遍又一遍地写 AutoResetEvent 东西,所以我决定创建一个方法。但是当我尝试从派生类 Bot : Activity

调用此方法时
EventParams eventResult = WaitEventRaise(ref currentJob.JobReported);

给予

Error 30 The best overloaded method match for Project.Activity.WaitEventRaise(ref System.EventHandler)' has some invalid arguments

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

public event EventHandler<JobReport> JobReported;

class JobReport : EventArgs

我想做的是有一个机器人做工作,实际上它创造工作并等待他们完成他们的工作。作业类在内部引发事件以使机器人类注意到它已完成其工作。机器人类一直等到作业引发事件。所以我希望它清楚。很抱歉英语不是我的母语。

最佳答案

基本上,您不能引用这样的事件。两种选择:

  • 传递“添加处理程序”和“删除处理程序”的委托(delegate):

    EventParams eventResult = 
    WaitEventRaise<JobReport>(handler => currentJob.JobReported += handler,
    handler => currentJob.JobReported -= handler);

    其中 WaitEventRaise 将被声明为:

    EventParams WaitEventRaise<T>(Action<EventHandler<T>> add,
    Action<EventHandler<T>> remove)
    where T : EventArgs
  • 传入与事件对应的EventInfo,您将通过反射获取它

这两个都不是非常令人愉快 - 这是 Rx 也遇到的问题。

关于c# - 将事件处理程序作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17947828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com