C#事件,将自定义参数传递给处理程序

本文关键字:处理 程序 参数传递 自定义 事件 | 更新日期: 2023-09-27 18:27:03

我正在寻找一种方法来做类似的事情

public void Download(string oid)
{
    Foo foo = Controller.Instance.GetFormation(oid);
    Request request = new Request (data);
    HttpResponseAction.Instance.OnFooDownloadedEvent += OnDoneDownloadAction(sender, event, request, foo);
}
private void OnDoneDownloadAction(object sender, OnLoadingEventArgs e, Request request, Foo foo)
{
      // Do something with my awesome args
}

因此,需要处理一个事件,附加一个方法来处理它,将事件参数传递给这个函数,再加上一些参数。

我需要用这种方式来做这件事,因为事件处理程序被添加了不止一次,并且我需要在从被处理的方法中触发good之后将其删除。

我该怎么做?

C#事件,将自定义参数传递给处理程序

我现在可以建议的一个解决方案

public void Download(string oid)
{
    Foo foo = Controller.Instance.GetFormation(oid);
    Request request = new Request (data);
    // create a local variable of required delegate type   
    EventHandler<OnLoadingEventArgs> handler = 
    (object sender, OnLoadingEventArgs ev)  => 
    { 
         // foo and request can be used here
         // if foo or request is used here, then it became captured variable
         // Do something with your awesome captured variables: foo and request
    };
    // subscribe to event
    HttpResponseAction.Instance.OnFooDownloadedEvent += handler;
    // unsubscribe event handler when necessary
    HttpResponseAction.Instance.OnFooDownloadedEvent -= handler;
    // you might want to return handler from method or store it somewhere
}

编辑你的问题我意识到,如果你喜欢的话,你仍然可以有一个命名的方法(但局部变量无论如何都被捕获了)

public void Download(string oid)
{
    Foo foo = Controller.Instance.GetFormation(oid);
    Request request = new Request (data);
    // create a local variable of required delegate type   
    EventHandler<OnLoadingEventArgs> handler = 
    (object sender, OnLoadingEventArgs ev)  => 
    OnDoneDownloadAction(sender, ev, request, foo);
    // subscribe to event
    HttpResponseAction.Instance.OnFooDownloadedEvent += handler;
    // unsubscribe event handler when necessary
    HttpResponseAction.Instance.OnFooDownloadedEvent -= handler;
    // you might want to return handler from method or store it somewhere
}
private void OnDoneDownloadAction(object sender, OnLoadingEventArgs e, Request request, Foo foo)
{
      // Do something with my awesome args
}

首先,您需要在某个地方定义一个代表事件处理程序的委托:

// This needs to be inside a namespace...
public delegate void FooDownloadEventHandler(object sender, OnLoadingEventArgs e, Request request, Foo foo);

然后对于OnFooDownloadEvent事件成员,您需要使用委托定义:

 public event FooDownloadEventHandler;

正如您在示例代码中所做的那样,订阅该事件。

我希望这就是你想要的。。。。

https://msdn.microsoft.com/en-us/library/ms173171.aspx

https://msdn.microsoft.com/en-us/library/8627sbea.aspx