码迷,mamicode.com
首页 > Windows程序 > 详细

C#事件复习

时间:2020-07-11 18:57:47      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:null   注册   委托   引用   new   hand   his   方法   mamicode   

遇到一本好书,终于把事件搞懂了。

技术图片

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 senderSystem.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

//事件实际上就是委托,委托就是类型安全的函数指针。

//所以此时,senderMyIntChanged委托,关联到receiver.GetNotificationFromSender方法。

sender.MyIntChanged += receiver.GetNotificationFromSender;

//接下去的步骤:

//调用属性的setset里面就有触发的事件函数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";

?

}

}

C#事件复习

标签:null   注册   委托   引用   new   hand   his   方法   mamicode   

原文地址:https://www.cnblogs.com/ifconfig/p/13284479.html

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