一佳一

记录像1+1一样简洁的代码

导航

事件传递数据

Posted on 2022-07-04 08:57  一佳一  阅读(15)  评论(0编辑  收藏  举报

派生的自定义类

    /// <summary>
    /// 派生自EventArgs的类,用于传递数据
    /// </summary>
    class PaperContentEventArgs:EventArgs
    {
        public string Name { get; set; }                    //用于存储数据,当事件被调用时,可利用其进行传递数据。
    }

发布者

/// <summary>
    /// 报社
    /// </summary>
    class NewspaperOffice 
    {
        //1、创建事件并发布
        public event EventHandler<PaperContentEventArgs> StartPublishPaper;    

        public void Publish()
        {            
            Console.WriteLine("已发布报纸!报社传递数据:阿辉");
            PaperContentEventArgs paperContent = new PaperContentEventArgs();
            paperContent.Name = "阿辉";
            
            //2、触发事件,通知订阅者收报纸进行阅读
            StartPublishPaper(this, paperContent);                                            
        }
    }

订阅者

/// <summary>
    /// 阿辉 订阅者
    /// </summary>
    class AhuiPeople 
    {
        public AhuiPeople(NewspaperOffice npo)
        {
            npo.StartPublishPaper += SubscriptinPaper;                    //3、订阅事件
        }

        void SubscriptinPaper(object sender, PaperContentEventArgs e)
        {            
            Console.WriteLine("阿辉接收到报纸,开始阅读!收到的传递数据为:"+e.Name);
        }
    }