---------------------------------------例一-------------------------------------------
public delegate void NumManipulationHandler();
class EventTest
{
public static int value;
public event NumManipulationHandler NumChanged;
public event NumManipulationHandler NumNotChanged;
public EventTest()//构造函数
{
int n = 6;
SetValue(n);
}
public void SetValue(int n)
{
if (value != n)
{
value = n;
OnNumChanged();
}
else
{
OnNumNotChanged();
}
}
protected virtual void OnNumChanged()
{
if (NumChanged != null)
{
NumChanged();//触发事件
}
else
{
Console.WriteLine(("NumChanged event not fire"));
Console.ReadKey();
}
}
protected virtual void OnNumNotChanged()
{
if (NumNotChanged != null)
{
NumNotChanged();//触发事件
}
else
{
Console.WriteLine(("NumNotChanged event not fire"));
Console.ReadKey();
}
}
}
class SubEvent
{
public void Changed()
{
Console.WriteLine("event fire,value changed:"+ EventTest.value);
Console.ReadKey();
}
public void NotChanged()
{
Console.WriteLine("event fire,value Notchanged:"+EventTest.value);
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
EventTest e = new EventTest();
SubEvent event1 = new SubEvent();
e.NumChanged += event1.Changed;
e.NumNotChanged += event1.NotChanged;
e.SetValue(7);
e.SetValue(11);
e.SetValue(11);
}
}
- 在这个例子中,Main()注册事件,每次SetValue时,只要value!=n,就会触发NumChanged(); 否则触发 NumNotChanged();
- 注册事件只需要注册一次就好,而触发事件是在一定条件下才能触发。
- 事件的作用就在于针对同一通知,做出不同响应。
---------------------------------------例二-------------------------------------------
public delegate void GoToBedHandler(string info);
class Wife
{
public event GoToBedHandler GoToBed;
public void Say(string info)
{
if(GoToBed!=null)
GoToBed(info);
}
}
class HusBand
{
public void GetInfo(string info)
{
Console.WriteLine("Husband"+info);
}
}
class Son
{
public void GetInfo(string info)
{
Console.WriteLine("Son"+info);
}
}
class Program
{
static void Main(string[] args)
{
Wife w=new Wife();
HusBand h=new HusBand();
w.GoToBed += h.GetInfo;
Son s=new Son();
w.GoToBed += s.GetInfo;
w.Say(" Go To Sleep");
}
}
- 注意:不可以在HusBand 或Son的构造函数中注册事件,因为不进行实例化HusBand或Son时会报错。而进行实例化后,会产生新的HusBand 或Son对象,与新创建的Wife 没有任何关系。