C# 事件
C#中的事件为,在某一条、状态等发生变化或变化时,通知另一个对象,然后另一对象接收到消息后,做出相应的反应。
举个例子: 妈妈在做饭,当妈妈做完饭之后通知孩子。当孩子收到到妈妈的消息,然后孩子立即去洗手,然后过来吃饭。
妈妈要计算一个从 1 到 N 的和,需要孩子帮忙计算
代码如下
public class Mother
{
//定义无参的委托
public delegate void CookingEndHandle();
//声明事件为 CookingEndHandle 类型
public event CookingEndHandle cookingEndEvent;
//定义包含一个 int 类型参数和 一个 int 类型返回值的委托CalculateHandle
public delegate int CalculateHandle(int num);
//声明事件为 CalculateHandle 类型
public event CalculateHandle calculateEvent;
private Children _children;
public Mother()
{
_children = new Children(this);
Cooking();
Calculate(100);
}
private void Cooking()
{
if (null != cookingEndEvent)
{
cookingEndEvent();
}
}
private void Calculate(int num)
{
if (null != calculateEvent)
{
int result = calculateEvent(num);
string msg = string.Format("从 1 加到 {0} 的和:{1} \n", num, result);
Console.WriteLine(msg);
}
}
}
public class Children
{
private Mother _mother;
public Children(Mother mother)
{
_mother = mother;
RegisterEvent();
}
// 注册消息
private void RegisterEvent()
{
//添加消息后,mother 调用 cookingEndEvent 的时候就会调用到 Children 的 CookingEnd函数
_mother.cookingEndEvent += CookingEnd;
//添加消息后,mother 调用 calculateEvent 的时候就会调用到 Children 的 Calculate
_mother.calculateEvent += Calculate;
}
// 移除消息
private void UnRegisterEvent()
{
//移除消息,mother 调用 cookingEndEvent 的时候不会触发 Children 的方法了
_mother.cookingEndEvent -= CookingEnd;
//移除消息,mother 调用 calculateEvent 的时候不会触发 Children 的方法了
_mother.calculateEvent -= Calculate;
}
// 接收妈妈做饭的通知
private void CookingEnd()
{
Console.WriteLine("好的我这就去洗手,然后过去吃饭 \n");
}
// 接收妈妈计算的通知
private int Calculate(int num)
{
// 帮妈妈计算从 1 加到 num 的总和
int sum = (1 + num) * num / 2;
return sum;
}
}
运行结果如下