1、一个节拍器,每3秒发出一个事件,接收者听到后说“HEARD IT”,本事例说明了怎样创建和传递事件。把下面的代码复制到控制台程序即可。
using System;
namespace wildert
{
public class Metronome
{
public event TickHandler Tick;
public EventArgs e = null;
public delegate void TickHandler(Metronome m, EventArgs e);
public void Start()
{
while (true)
{
System.Threading.Thread.Sleep(3000);
if (Tick != null)
{
Tick(this, e);
}
}
}
}
public class Listener
{
public void Subscribe(Metronome m)
{
m.Tick += new Metronome.TickHandler(HeardIt);
}
private void HeardIt(Metronome m, EventArgs e)
{
System.Console.WriteLine("HEARD IT");
}
}
class Test
{
static void
Main
()
{
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m);
m.Start();
}
}
}
2、进一步说明怎样传递参数
using System;
namespace wildert
{
public class TimeOfTick : EventArgs
{
private DateTime TimeNow;
public DateTime Time
{
set
{
TimeNow = value;
}
get
{
return this.TimeNow;
}
}
}
public class Metronome
{
public event TickHandler Tick;
public delegate void TickHandler(Metronome m, TimeOfTick e);
public void Start()
{
while (true)
{
System.Threading.Thread.Sleep(3000);
if (Tick != null)
{
TimeOfTick TOT = new TimeOfTick();
TOT.Time = DateTime.Now;
Tick(this, TOT);
}
}
}
}
public class Listener
{
public void Subscribe(Metronome m)
{
m.Tick += new Metronome.TickHandler(HeardIt);
}
private void HeardIt(Metronome m, TimeOfTick e)
{
System.Console.WriteLine("HEARD IT AT {0}",e.Time);
}
}
class Test
{
static void
Main
()
{
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m);
m.Start();
}
}
}