场景: 假设你是一家婚礼策划公司的组织者,你需要安排婚礼的各个方面,如音乐、鲜花、照片等。
事件的用法: 你创建了一个婚礼策划事件,并邀请了音乐师、花店、摄影师等作为订阅者。当婚礼日期临近时,你触发婚礼策划事件,所有订阅者会按照自己的职责做好准备。文章来源:https://www.toymoban.com/news/detail-767699.html
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://www.toymoban.com/news/detail-767699.html
到了这里,关于【C#】关于事件的使用ii,eg:{婚礼策划公司的组织者}的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!