VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Objective-C编程 >
  • 利用绑定反射事件处理程序c#

制作者:剑锋冷月 单位:无忧统计网,www.51stat.net
 

 

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

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


相关教程