C# 事件

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;
    }
}

运行结果如下
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值