using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public static void Main(string[] args)
{
//实例化对象
Mom mom = new Mom();
Dad dad = new Dad();
Child child = new Child();
//C#发布和订阅
//将爸爸和孩子的Eat方法注册到妈妈的MakeCooking事件
//订阅妈妈开饭的消息
mom.MakeCooking += dad.Eat;
mom.MakeCooking += child.Eat;
//调用妈妈的Cook事件
mom.Cook();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
public class Mom
{
//定义MakeCooking事件,用于发布做饭消息
public event Action MakeCooking;
public void Cook()
{
Console.WriteLine("妈妈 : 饭好了,赶紧来吃饭");
//饭做好了,发布消息
MakeCooking?.Invoke();
}
}
public class Dad
{
public void Eat()
{
Console.WriteLine("爸爸 : 好的,抽完这根烟马上就来吃饭。");
}
}
public class Child
{
public void Eat()
{
Console.WriteLine("孩子 : 好的,打完这局游戏再吃。");
}
}
}