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("妈妈 : 饭好了,赶紧来吃饭");
C# 事件发布和订阅
最新推荐文章于 2024-05-17 20:55:48 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)