【C#】关于事件的使用ii,eg:{婚礼策划公司的组织者}

2023-12-29 22:45:09

场景: 假设你是一家婚礼策划公司的组织者,你需要安排婚礼的各个方面,如音乐、鲜花、照片等。
事件的用法: 你创建了一个婚礼策划事件,并邀请了音乐师、花店、摄影师等作为订阅者。当婚礼日期临近时,你触发婚礼策划事件,所有订阅者会按照自己的职责做好准备。

using System ;
public class WeddingPlanner
{
    public event EventHandler WeddingPlanningEvent;

    public void PlanWedding()
    {
        // 策划婚礼的各个方面...

        // 触发婚礼策划事件
        WeddingPlanningEvent?.Invoke(this, EventArgs.Empty);
        //WeddingPlanningEvent 是一个 EventHandler 类型的事件,它的委托要求传递两个参数,
        //	即事件的源(this,表示 WeddingPlanner 实例)和事件参数(空的 EventArgs 实例)
    }
}

public class Musician
{
    public void PlayMusic(object sender, EventArgs e)
    {
        Console.WriteLine("Musician: Playing romantic music");
    }
}

public class Florist
{
    public void ArrangeFlowers(object sender, EventArgs e)
    {
        Console.WriteLine("Florist: Arranging beautiful flowers");
    }
}

public class Photographer
{
    public void CaptureMoments(object sender, EventArgs e)
    {
        Console.WriteLine("Photographer: Capturing precious moments");
    }
}

class Program
{
    static void Main()
    {
        WeddingPlanner planner = new WeddingPlanner();
        Musician musician = new Musician();
        Florist florist = new Florist();
        Photographer photographer = new Photographer();

        // 订阅婚礼策划事件
        planner.WeddingPlanningEvent += musician.PlayMusic;
        planner.WeddingPlanningEvent += florist.ArrangeFlowers;
        planner.WeddingPlanningEvent += photographer.CaptureMoments;

        // 策划婚礼
        planner.PlanWedding();

        Console.ReadLine();
    }
}

Musician: Playing romantic music
Florist: Arranging beautiful flowers
Photographer: Capturing precious moments

ps: 觉得有用 就留个赞再走吧 xiexie

文章来源:https://blog.csdn.net/weixin_44939430/article/details/135200427
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。