2011-04-04 58 views
0

我對使用C#事件處理很新。我們的應用有以下事件定義:C# - 關於事件的問題

public sealed class MonitorCallback : IMonitorCallback 
{ 
    public event EventHandler<ApplyEventArgs> ApplyAccepted; 
    public event EventHandler<ApplyEventArgs> ApplyRejected; 
} 

我需要編寫一些代碼來處理,當他們被解僱應對這些事件。有人能讓我開始如何做到這一點嗎?

+2

雖然我不是不利於幫助你,你能不能要求你的團隊中的人寫他們? – 2011-04-04 14:14:29

回答

2

當您開始在下面輸入+=並點擊TAB時,Visual Studio將自動爲事件處理函數創建存根。

protected MyMonitorCallback MonitorCallback; 
public class MyClass 
{ 
    void Main() 
    { 
      MyMonitorCallback = new MonitorCallback(); 
      MyMonitorCallback.ApplyAccepted += new EventHander<ApplyEventArgs>(MyMonitorCallback_ApplyAccepted); 
    } 
    void MyMonitorCallback_ApplyAccepted(object sender, ApplyEventArgs e) { 
     .. 
    } 
} 
+0

一個EventHander 委託也有一個發件人屬性...所以你的代碼應該是MyMonitorCallback_ApplyAccepted(對象發件人,ApplyEventArgs e) – m0sa 2011-04-04 14:20:22

+0

糟糕。糾正。 – 2011-04-04 14:21:59

2

開始將在MSDN tutorial 這將通過申報,並調用掛鉤的事件的最佳地點。

對於代表(another msdn tutorial)的閱讀也是一個不錯的主意,因爲您可以在事件處理中使用它們,從頭開始理解它是個不錯的主意。

0

當您創建MonitorCallback實例時,您將事件訂閱到要寫入的事件處理函數。語法看起來是這樣的,

public class MonitorCallbackFactory{ 

    public MonitorCallback CreateCallback(){ 
     // create the callback instance 
     var callback = new MonitorCallback(); 

     // subscribe the events to the EventHandler. 
     callback.ApplyAccepted += OnApplyAccepted; 
     callback.ApplyRejected += OnApplyRejected; 

     return callback; 
    } 

    protected virtual void OnApplyAccepted(object sender, ApplyEventArgs e){ 
      // the sender is always the type of object that raises the event, so 
      // if you need it strongly typed you can do: 
      var callback = (MonitorCallback)sender; 
      // then write your code for what happens when 
      // the ApplyAccepted event is raised here 
    } 

    protected virtual void OnApplyRejected(object sender, ApplyEventArgs e){ 
      // write your code for what happens when 
      // the ApplyRejected event is raised here 
    } 

} 

正如你可以看到+=是訂閱一個處理一個事件的語法。 -=是取消訂閱和事件處理程序的語法。

0

我認爲你已經有這樣的代碼;

public class EventExample 
{ 
    private EventHandler<ApplyEventArgs> m_evApplyAccepted; 
    public event EventHandler<ApplyEventArgs> ApplyAccepted 
    { 
     add { m_evApplyAccepted += value; } 
     remove { m_evApplyAccepted -= value; } 
    } 
    protected virtual void OnEventName(ApplyEventArgs e) 
    { 
     if (m_evApplyAccepted != null) 
      m_evApplyAccepted.Invoke(this, e); 
    } 
    public class ApplyEventArgs : EventArgs { } 
} 

你消耗這樣的事件,

public class EventConsumer 
{ 
    private EventExample eventExample; 
    public EventConsumer() 
    { 
     eventExample = new EventExample(); 

     //register a handler with the event here 
     eventExample.ApplyAccepted += new EventHandler<EventExample.ApplyEventArgs>(eventExample_EventName); 
    } 

    void eventExample_EventName(object sender, EventExample.ApplyEventArgs e) 
    { 
     //respond to event here 
    } 
}