C#事件的簡單認識

來源:互聯網
上載者:User

標籤:

 事件是C#的一個重要特性。事件主要涉及發行者,訂閱者,以及事件處理常式。

 使用.net 類庫中預定義的委託類型可以很方便的定義事件。    發行者觸發事件後,訂閱者即執行事件處理函數:代碼及運行結果如下:

   

 public class Yiqiok            //事件發行者    {        public event EventHandler LolInvite;  //使用.NET類庫預定義的委託類型定義事件        public void InviteComing(string msg)  //發出事件        {            if(LolInvite!=null)   //檢查是否添加了事件處理方法            {                Console.WriteLine(msg);                LolInvite(this, new EventArgs());  //觸發事件            }        }            }    public class Classmate  //事件訂閱者    {        private string name;        public Classmate (string Name)        {            name = Name;        }        public void SendResponse(object s,EventArgs e)  //事件處理函數,要與預定義委託類型匹配        {            Console.WriteLine("來自:" + this.name + "的回複: 已經收到邀請,隨時可以開始!");        }    }    public class Start    {        static void Main()        {            Yiqiok yiqiok = new Yiqiok();//初始化            Classmate classmate1 = new Classmate("Lna");            Classmate classmate2 = new Classmate("Jim");            Classmate classmate3 = new Classmate("Cry");            Classmate classmate4 = new Classmate("Tom");            yiqiok.LolInvite += new EventHandler(classmate1.SendResponse);//訂閱事件            yiqiok.LolInvite += new EventHandler(classmate2.SendResponse);            yiqiok.LolInvite += new EventHandler(classmate3.SendResponse);            yiqiok.LolInvite += new EventHandler(classmate4.SendResponse);            yiqiok.InviteComing("yiqiok:五人開黑來不來???");  //發出通知        }    }

 

C#事件的簡單認識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.