2015-12-16 32 views
1

进出口寻找一个方式做这样的事情C#事件,通过自定义的参数传递给处理程序

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 
} 

因此需要处理的事件,重视处理它的方法,传递事件参数给这个函数加上一些另外还有一些参数。

我需要,因为事件处理程序被添加不止一次这样做那样,我需要从处理方法触发后,将其删除的好。

我该怎么做?

+1

'OnFooDownloadedEvent':它有一个'事件处理程序'型或其他一些? – ASh

+0

是的,它有一个附加 – Leze

回答

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 
} 
+0

真棒。由于火山灰我一直在寻找,但不知道如何使用它。现在我可以 – Leze

+0

@Leze,很好:)也检查更新的答案 – ASh

+0

非常感谢您的更新答案,它是我寻找的100%,你的第一个答案也完成了这项工作。 – Leze

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

+0

感谢您的文档链接,帮助我更加理解了上面的答案。 – Leze

+0

没问题。快乐的编码! –

相关问题