码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-09-16 12:24:00      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:io   ar   sp   cti   on   c   line   ad   new   

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

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

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

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

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

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

标签:io   ar   sp   cti   on   c   line   ad   new   

原文地址:http://www.cnblogs.com/dlbird/p/3974597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!