将MethodInfo转化为Delegate的方式
来源:互联网 发布:工厂布局仿真软件 编辑:程序博客网 时间:2024/05/29 17:23
有时再用反射的时候,需要将反射出的方法注册给某个事件,这是就需要将改方法转化为delegate后才能绑定到对应的事件上
可以通过Delegate.CreateDelegate的方法来实现,如下:
/// <summary> /// 生成反射过来的MethodInfo到指定类型的委托 /// </summary> /// <typeparam name="T">EventArgs泛型类型</typeparam> /// <param name="instance">当前对象</param> /// <param name="method">需要转化为delegate的方法</param> /// <returns></returns> public static Delegate CreateDelegateFromMethodInfo<T>(Object instance,MethodInfo method) where T:EventArgs//约束泛型T只能是来自EventArgs类型的 { Delegate del = Delegate.CreateDelegate(typeof(EventHandler<T>), instance, method); EventHandler<T> mymethod = del as EventHandler<T>; return mymethod; } /// <summary> /// 生成反射过来的MethodInfo到指定类型的委托 /// </summary> /// <typeparam name="T">EventHandle泛型类型</typeparam> /// <param name="instance">当前对象</param> /// <param name="method">需要转化为delegate的方法</param> /// <returns></returns> public static Delegate CreateDelegateFromMethodInfoByDelegate<T>(Object instance, MethodInfo method) { Delegate del = Delegate.CreateDelegate(typeof(T), instance, method); EventHandler mymethod = del as EventHandler; return mymethod; }
private void button3_Click(object sender, EventArgs e) { var Instance = Activator.CreateInstance(typeof(Form1)) as Form1; MethodInfo methodInfo = typeof(Form1).GetMethod("Method1"); EventHandler dd = Delegate.CreateDelegate(typeof(EventHandler), Instance,methodInfo) as EventHandler; dd(null, null); }public void Method1(object sender, EventArgs e) { MessageBox.Show("ee"); }
0 0
- 将MethodInfo转化为Delegate的方式
- 将MethodInfo转化为Delegate的方式
- 比较将字符串转化为整数的几种方式
- java方式的将java对象以及list或者map转化为json数据
- java方式的将java对象以及list或者map转化为json数据 .
- java方式的将java对象以及list或者map转化为json数据 .
- 用指针的方式将某年某月转化为某年中的第几天
- 将Double类型的数字转化为金额方式xx,xx.xx
- 阻止a标签跳转,且将a的get提交方式转化为post提交
- 将数值转化为字符串的函数
- 将阿拉伯数字转化为人民币的大写
- 将字符转化为对应的数字
- 将List转化为数组的若干问题
- 将数值转化为字符串的函数
- 将vs2012的项目转化为vs2010
- 将VS2012的项目转化为VS2010
- 将密码转化为SAP的格式
- 将文件转化为字符串的方法
- nginx的使用
- mysql 用保留字作为列名
- 瑞典的城市垃圾自动处理系统
- 安卓开发工具快速配置环境变量--jdk安装步骤及配置环境变量、Android Studio、Eclipse配置环境变量
- nyoj222 整数中的1 填表法 带思路
- 将MethodInfo转化为Delegate的方式
- JVM内存区域
- Xamarin.Android 集成 微支付 和 支付宝 支付 (成功!)
- Java反射机制
- VI命令
- 关于主机连接虚拟机centOS中的redis
- 创建型模式-工厂方法(factory_method)
- 小范围排序
- 51Nod 1712 区间求和