委託與事件使用精簡案例—將複雜問題簡單化

來源:互聯網
上載者:User

網上關於委託與事件的使用方法和例子有很多,看得確實頭暈,講了使用事件的大致步驟:

1.  聲明關於事件的委託;

2.  聲明事件;

3. 編寫觸發事件的函數;

4. 建立事件處理常式;

5. 註冊事件處理常式;

6. 在適當的條件下觸發事件。 

個人覺得其實就分為大致四步,結合下面案例:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace VistaRenderer{    public partial class LearnEvent : Form    {        //1.定義委託        public delegate void WuEvent(object sender, TestEventArgs e);        //2.定義事件        public event WuEvent wuEvent;        //事件在表單構造方法中使用        public LearnEvent()        {            InitializeComponent();            //3.註冊事件            wuEvent += new LearnEvent.WuEvent(processEvent);            //4.下面兩步才是真正呼叫事件處理自己想要的內容,即觸發事件            TestEventArgs e = new TestEventArgs("我愛你");            wuEvent(this,e);        }        //定義自己的處理方法        void processEvent(object sender, TestEventArgs e)        {            MessageBox.Show(e.Name);        }              }    //定義事件參數類    public class TestEventArgs : EventArgs    {        public  string Name;        public TestEventArgs(string name)        {            this.Name = name;        }    }    }

這是一個form表單,可以直接拷到vs2008上面運行下。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.