欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#中事件的动态调用实现方法

时间:2021-07-31 08:04:57|栏目:.NET代码|点击:

本文实例讲述了C#动态调用事件的方法。一般来说,传统的思路是,通过Reflection.EventInfo获得事件的信息,然后使用GetRaiseMethod方法获得事件被触发后调用的方法,再使用MethodInfo.Invoke来调用以实现事件的动态调用。

但是很不幸的,Reflection.EventInfo.GetRaiseMethod方法始终返回null。这是因为,C#编译器在编译并处理由event关键字定义的事件时,根本不会去产生有关RaiseMethod的元数据信息,因此GetRaiseMethod根本无法获得事件触发后的处理方法。Thottam R. Sriram 在其Using SetRaiseMethod and GetRaiseMethod and invoking the method dynamically 一文中简要介绍了这个问题,并通过Reflection.Emit相关的方法来手动生成RaiseMethod,最后使用常规的GetRaiseMethod来实现事件触发后的方法调用。这种做法比较繁杂。

以下代码是一个简单的替代方案,同样可以实现事件的动态调用。具体代码如下:

public event EventHandler<EventArgs> MyEventToBeFired;  
public void FireEvent(Guid instanceId, string handler)    
{     
  // Note: this is being fired from a method with in the same class that defined the event (i.e. "this").      
  EventArgs e = new EventArgs(instanceId);  
  MulticastDelegate eventDelagate = (MulticastDelegate)this 
   .GetType()  
   .GetField(handler, BindingFlags.Instance | BindingFlags.NonPublic)
   .GetValue(this);  
  Delegate[] delegates = eventDelagate.GetInvocationList();  
  foreach (Delegate dlg in delegates)  
  {  
    dlg.Method.Invoke( dlg.Target, new object[] { this, e } );  
  }  
}  
FireEvent(new Guid(), "MyEventToBeFired");

希望本文所述对大家的C#程序设计有所帮助

上一篇:由于扩展配置问题而无法提供您请求的页面错误解决方法

栏    目:.NET代码

下一篇:C#实现百度网站收录和排名查询功能思路及实例

本文标题:C#中事件的动态调用实现方法

本文地址:http://www.codeinn.net/misctech/163050.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有