分享

利用反射获得委托和事件以及创建委托实例和添加事件处理程序

 昵称10504424 2012-08-02
近一些都在看关于反射的内容,然后在网上大多数都是通过反射获得类型中方法,属性、字段这样的文章, 但是对于如何获得委托类型怎么去实现的却没有, 所以写下这边篇文章来让自己以后很好的复习以及想了解的朋友做参考。

一、 利用反射获得委托类型并创建委托实例

复制代码
using System;
using System.Reflection;
namespace ConsoleApplication1
{
public  class Test
{
public delegate void delegateTest(string s);
public void method1(string s)
{
Console.WriteLine("Create Delegate Instance: " + s);
}
}
class Program
{
static void Main(string[] args)
{
Test test = new Test();
Type t = Type.GetType("ConsoleApplication1.Test");
// 因为委托类型编译后是作为类的嵌套类型的,所以这里通过GetNestedType(String s)的方法来获得委托类型。
Type nestType = t.GetNestedType("delegateTest");
MethodInfo method =test.GetType().GetMethod("method1",  BindingFlags.Public | BindingFlags.Static|BindingFlags.Instance);
if (method != null)
{
// 创建委托实例
Delegate method1 = Delegate.CreateDelegate(nestType, test, method);
//动态调用委托实例
method1.DynamicInvoke("Hello");
}
Console.Read();
}
}
}
复制代码


二、 利用反射获得事件类型和绑定事件处理程序

复制代码
using System;
using System.Reflection;
namespace ConsoleApplication2
{
public class Test
{
public event EventHandler TestEvent;
public void Triggle()
{
if (TestEvent != null)
{
TestEvent(this, null);
}
}
}
class Program
{
static void Main(string[] args)
{
Test testT=new Test();
EventInfo eventinfo = typeof(Test).GetEvent("TestEvent");
if (eventinfo != null)
{
// 为事件动态绑定处理程序
eventinfo.AddEventHandler(testT, new EventHandler(triggleEvent));
testT.Triggle();
}
Console.Read();
}
public static void triggleEvent(object sender, EventArgs e)
{
Console.WriteLine("Event has been Triggled");
}
}
}
复制代码

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多