2011-04-04 59 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 
    } 
}