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

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

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

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");
        }
    }
}


希望这些使大家对放射有个更好的理解。

 

posted @ 2012-07-08 17:47  Learning hard  阅读(1779)  评论(3编辑  收藏  举报