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

时间:2015-12-16 11:03:24

标签: c# events delegates

我正在寻找一种方法来做那样的事情

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
}

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

我需要以这种方式执行此操作,因为事件处理程序被多次添加,我需要在触发处理方法中的商品后将其删除。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

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

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
}

答案 1 :(得分:0)

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

// 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