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