2015-12-16 57 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

沒問題。快樂的編碼! –

相關問題