遇到一本好书,终于把事件搞懂了。
using System;
class Sender
{
private int myInt;//字段
public int MyInt//属性
{
get{return myInt;} //获取get
set
{
myInt = value;//赋值
//Whenever we set a new value, the event will fire.
//就是每次给字段赋值后,触发事件
OnMyIntChanged();
}
}
?
//啰嗦解释一下:这里是"声明事件",事件实际上就是委托,委托就是类型安全的函数指针。
//前面有关键字event+关键字EventHandler组成
public event EventHandler MyIntChanged;
public void OnMyIntChanged() //配套的事件方法,前面加了On字。
{
if(MyIntChanged != null)
{
MyIntChanged(this, EventArgs.Empty);
}
}
//可以被事件关联的方法,但是需要遵循事件标准格式,就是参数里面必须有
//object sender,System.EventArgs e 这两个参数
//设置好标准参数,关联好方法,事件就可以"为所欲为了"。
public void GetNotificationItself(Object sender, System.EventArgs e)
{
Console.WriteLine("Sender himself send a notification: 我已经改变了myint的值为{0} ", myInt);
}
}
?
class Receiver
{
public void GetNotificationFromSender(Object sender, System.EventArgs e)
{
Console.WriteLine("Receiver类 receives a notification: Sender类最近改变了myInt的值 . ");
}
}
?
class Program
{
static void Main(string[] args)
{
//实例化Sender类
Sender sender = new Sender();
//实例化Receiver类
Receiver receiver = new Receiver();
//Receiver is registering for a notification from sender
//事件实际上就是委托,委托就是类型安全的函数指针。
//所以此时,sender的MyIntChanged委托,关联到receiver.GetNotificationFromSender方法。
sender.MyIntChanged += receiver.GetNotificationFromSender;
//接下去的步骤:
//①调用属性的set,set里面就有触发的事件函数OnMyIntChanged();
//②触发事件函数OnMyIntChanged(),里面再次MyIntChanged(this, EventArgs.Empty);一下
//③此时委托一下,this就是类receiver,事件参数消息设置为空EventArgs.Empty;
//④运行Console.WriteLine("Receiver receives a notification: Sender recently has changed the myInt value . ");
sender.MyInt = 1;//Receiver receives a notification: Sender类最近改变了 myInt 的值 . "
sender.MyInt = 2;//"Receiver receives a notification: Sender类最近改变了 myInt 的值 . "
//Unregistering now,名词叫做反注册,实际就是删除引用关联(函数指针重新设置为null)
sender.MyIntChanged -= receiver.GetNotificationFromSender;
//No notification sent for the receiver now.再也不会调用GetNotificationFromSender了
sender.MyInt = 3;
//===========================================================
//===========================================================
//事件(委托)再次关联sender.GetNotificationItself
sender.MyIntChanged += sender.GetNotificationItself;
sender.MyInt = 4;//"Sender himself send a notification: 我已经改变了myint的值为 4";
?
}
}