WEB开发网
开发学院软件开发C语言 利用反射绑定事件处理程序(C#) 阅读

利用反射绑定事件处理程序(C#)

 2010-09-30 20:58:11 来源:WEB开发网   
核心提示:传统的写法:强类型的情况下usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Reflection;namespaceConsoleApplication3{classProgram{staticvoidMain(string

传统的写法:强类型的情况下

using System;
using System.Collections.Generic;
using System.Text; 
using System.Reflection; 
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer c = new Customer();
            c.OnChange += new EventHandler(c_OnChange); 
            c.Change();
            Console.Read(); 
        } 
        static void c_OnChange(object sender, EventArgs e)
        {
            Console.WriteLine("事件被触发了");
        }
    } 
    class Customer
    {
        public event EventHandler OnChange;
        public void Change()
        {
            if (OnChange != null)
                OnChange(this, null);
        }
    }
} 

值得了解的另外一个写法

using System;
using System.Collections.Generic;
using System.Text; 
using System.Reflection; 
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer c = new Customer();
            EventInfo evt = c.GetType().GetEvent("OnChange",
                    BindingFlags.NonPublic | BindingFlags.Instance
                    | BindingFlags.Public
                ); 
            evt.AddEventHandler(c, new EventHandler(c_OnChange)); 
            c.Change();
            Console.Read(); 
        } 
        static void c_OnChange(object sender, EventArgs e)
        {
            Console.WriteLine("事件被触发了");
        }
    } 
    class Customer
    {
        public event EventHandler OnChange;
        public void Change()
        {
            if (OnChange != null)
                OnChange(this, null);
        }
    }
}

Tags:利用 反射 绑定

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接