`
CanBeatle
  • 浏览: 166916 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

详细探讨delegate(委托)和event(事件)(3)

    博客分类:
  • C#
阅读更多

event

 

        上一篇(http://canbeatle.iteye.com/blog/686201)我们通过IL查看了委托的实现方式。现在开始探讨event(事件)。

         .NET Framework 可以广泛地将委托用于事件处理任务,如 Windows 或 Web 应用程序中的按钮 Click 事件。Java 中的事件处理通常通过实现自定义侦听器类完成,而 C# 开发人员则可以利用委托处理事件。事件的声明类似于具有委托类型的字段,区别在于事件声明前面有 event 关键字。事件通常被声明为public,但允许使用任何可访问性修饰符。下面的示例演示了 delegateevent 的声明。  

// 声明委托   
public delegate void CustomEventHandler(object sender,System.EventArgs e);   
// 声明事件   
public event CustomEventHandler CustomEvent; 

 

    事件委托是多路广播的,这意味着它们可以对多个事件处理方法进行引用。通过维护事件的已注册事件处理程序列表,委托为引发事件的类担当事件发送器的角色。下面的示例演示如何为多个函数订阅事件。EventClass 类包含委托、事件和调用事件的方法。请注意调用事件只能从声明该事件的类内部进行。然后,TestEvents 类使用 += 运算符订阅事件,并使用 -= 运算符取消订阅。调用 InvokeEvent 方法时,它将激发事件,所有订阅了该事件的函数也同步激发,如下面的示例所示: 

public class EventClass    
{    
// 声明委托    
public delegate void CustomEventHandler(object sender, System.EventArgs e);    
// 声明事件    
public event CustomEventHandler CustomEvent;    
  
public void InvokeEvent()    
{    
// 调用事件,注意,一但调用,就是触发所有的event,而不是第一个
   CustomEvent(this, System.EventArgs.Empty);   
 /*另外一种调用方式 if (CustomEvent != null)   
{  
  foreach (Delegate delItem in CustomEvent.GetInvocationList())   
 {   
   delItem.DynamicInvoke(this, System.EventArgs.Empty);  
  }  
 }  
 */  
 }    
}    
class TestEvents   
{    
  private static void CodeToRun(object sender, System.EventArgs e)  
  {    
   System.Console.WriteLine("CodeToRun is executing");    
  }    
  
  private static void MoreCodeToRun(object sender, System.EventArgs e)    
  {   
   System.Console.WriteLine("MoreCodeToRun is executing");    
  }    
  static void Main()   
  {    
   EventClass ec = new EventClass(); ec.CustomEvent += new EventClass.CustomEventHandler(CodeToRun);    
   ec.CustomEvent += new EventClass.CustomEventHandler(MoreCodeToRun);    
   System.Console.WriteLine("First Invocation:"); ec.InvokeEvent();   
   ec.CustomEvent -= new EventClass.CustomEventHandler(MoreCodeToRun);    
   System.Console.WriteLine("\nSecond Invocation:");    
   ec.InvokeEvent();    
  }   
}   

 

这是反汇编的代码结构:

 

event反汇编代码结构

 

通过ildasm反汇编可以看到 public event CustomEventHandler CustomEvent 声明了两个成员

 

 .field private class EventDelegateTest.EventClass/CustomEventHandler CustomEvent

和对CustomEvent的一个包装:

 

 .event EventDelegateTest.EventClass/CustomEventHandler CustomEvent
{
  .addon instance void EventDelegateTest.EventClass::add_CustomEvent(class EventDelegateTest.EventClass/CustomEventHandler)
  .removeon instance void EventDelegateTest.EventClass::remove_CustomEvent(class EventDelegateTest.EventClass/CustomEventHandler)
}

 

其中在CustomEvent上的+=和-=分别对应add_CustomEvent和remove_CustomEvent操作。

 

下一篇,从网上转了一篇文章来更深入的探讨delegate和event。

  • 大小: 98.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics