C#中委托的应用

本文通过C#中的委托,展示了如何在 Monster、Player、Panel 和 CJ 类之间实现对象间的事件传递,当怪物死亡时,不同角色根据委托处理金钱或计数。实例详细讲解了委托的使用和多路复用功能。
摘要由CSDN通过智能技术生成

C#中委托的应用案例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp18
{   
    class Monster
    {
        public Action<Monster> deadDoSomething;

        public int money = 10;

        public void Dead()
        {
            if(deadDoSomething!=null)
            {
                deadDoSomething(this);
            }
            deadDoSomething = null;
        }

    }

    class Player
    {
        private int myMoney = 0;

        public void MonsterDeadDoSomething(Monster m)
        {
            myMoney += m.money;
            Console.WriteLine("现在有{0}钱", myMoney);
        }
    }

    class Panel
    {
        private int nowShowMoney = 0;

        public void MonsterDeadDoSomething(Monster m)
        {
            nowShowMoney += m.money;
            Console.WriteLine("现在有{0}元钱", nowShowMoney);
        }
    }

    class CJ
    {
        private int nowKillMonsterNum = 0;

        public void MonsterDeadDo(Monster m)
        {
            nowKillMonsterNum += 1;
            Console.WriteLine("当前击杀了{0}怪物", nowKillMonsterNum);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Monster monster = new Monster();
            Player p = new Player();
            Panel panel = new Panel();
            CJ cj = new CJ();

            monster.deadDoSomething += p.MonsterDeadDoSomething;
            monster.deadDoSomething += panel.MonsterDeadDoSomething;
            monster.deadDoSomething += cj.MonsterDeadDo;

            monster.Dead();

            Monster monster2 = new Monster();
            monster2.deadDoSomething += p.MonsterDeadDoSomething;
            monster2.deadDoSomething += panel.MonsterDeadDoSomething;
            monster2.deadDoSomething += cj.MonsterDeadDo;

            monster2.Dead();

        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值