C#委托+事件的简单运用

现用一个简单的工具人 来实现简单的事件+委托
不是很难,所以话不多说,直接上代码。
主要自己记录一下,方便以后回来看看

using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate_Event
{
    //定义委托
    delegate void DownStairDelegate();
    
     /// <summary>
    /// 工具人类
    /// </summary>
    internal  class ToolMan
    {
        public string Name { get; set; }

        //event 事件是一种特殊的委托,或者说是受限制的委托,是委托的一种特殊应用,只能施加+=或者-=操作符。二者本质上是一个东西
        public event DownStairDelegate DownStairDelegate = null;
        public ToolMan(string name)
        {
            Name = name;
        }

        /// <summary>
        /// 工具人调用委托
        /// </summary>
        public void DownStair()
        {
            Console.WriteLine("工具人"+Name+"下楼了");
            if(DownStairDelegate!=null)
            DownStairDelegate();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate_Event
{
    public class LazyMan
    {
        public string Name { get; set; }

        public LazyMan(string name)
        {
            Name = name;
        }
        public void TakeFood()
        {
            Console.WriteLine("给"+Name+"拿外卖");
        }
        public void TakePackage()
        {
            Console.WriteLine("给"+Name+"拿快递");
        }
    }
}
using System;

namespace Delegate_Event
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ToolMan tool = new ToolMan("小明");

            LazyMan lazy1 = new LazyMan("张三");
            LazyMan lazy2 = new LazyMan("李四");
            LazyMan lazy3 = new LazyMan("王五");

            tool.DownStairDelegate += lazy1.TakeFood;
            tool.DownStairDelegate += lazy2.TakePackage;
            tool.DownStairDelegate+=lazy3.TakeFood;
            tool.DownStair();

            tool.DownStairDelegate-=lazy3.TakeFood;
            tool.DownStair();
            
            Console.WriteLine("Hello World!");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值