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

作者:shichen2014 时间:2022-08-29 03:27:28 

本文实例讲述了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#程序设计有所帮助

标签:C#,事件,动态,调用
0
投稿

猜你喜欢

  • 关于java关键字this和super的区别和理解

    2022-08-01 14:33:09
  • 详解Mybatis通用Mapper介绍与使用

    2023-11-29 08:49:08
  • 关于C#操作文件路径(Directory)的常用静态方法详解

    2023-06-06 10:40:12
  • JavaWeb开发之使用jQuery与Ajax实现动态联级菜单效果

    2023-11-28 19:46:08
  • C++实现LeetCode(131.拆分回文串)

    2023-07-24 09:58:42
  • Java 客户端操作 FastDFS 实现文件上传下载替换删除功能

    2022-06-01 15:01:38
  • Mybatisplus主键生成策略算法解析

    2022-06-22 20:49:23
  • 关于Scanner对象的输入结束标记问题

    2022-02-20 08:02:11
  • C#通过链表实现队列的方法

    2023-06-19 15:14:17
  • 浅谈Java 类中各成分加载顺序和内存中的存放位置

    2022-12-23 17:24:23
  • Java使用RedisTemplate模糊删除key操作

    2023-06-24 06:45:25
  • spring boot项目没有mainClass如何实现打包运行

    2021-10-24 11:29:20
  • Jenkins的安装配置详解

    2023-08-27 11:31:42
  • Java 定时器(Timer,TimerTask)详解及实例代码

    2022-08-17 20:03:11
  • java基于swing实现的五子棋游戏代码

    2023-09-24 17:31:17
  • SpringBoot加载应用事件监听器代码实例

    2023-06-15 14:28:07
  • SpringBoot新手入门的快速教程

    2021-09-28 23:23:25
  • Java中死锁与活锁的具体实现

    2023-10-29 01:48:02
  • Spring创建bean对象三种方式代码实例

    2023-02-04 08:53:33
  • MyBatis执行Sql的流程实例解析

    2022-06-12 19:43:42
  • asp之家 软件编程 m.aspxhome.com