傳統的寫法:強型別的情況下
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);
}
}
}