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