星期一, 5月 26, 2008

對class撰寫event

有時我們在處理class時..要撰寫物件的event..來讓其他的物件訂閱..
寫下簡單的範例.. 以後需要時自己也不會忘掉..

使用內建的delegate(EventHandler)去做
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

//建立測試按鈕事件
private void button1_Click(object sender, EventArgs e)
{
ukhs obj = new ukhs();

//加入訂閱事件
obj.myEvent += new EventHandler(obj_myEvent);

//測試
obj.goFire();
}

void obj_myEvent(object sender, EventArgs e)
{
if (e is myEvenArg)
{
MessageBox.Show((e as myEvenArg).msg);
}
}
}
}

//自行寫的class
class ukhs
{
//使用內建的delegate,他需要傳遞(object sender,eventArgs e)
public event EventHandler myEvent;
public void goFire()
{
if (myEvent != null)
{
myEvent(this, new myEvenArg("發射飛彈!!"));
}
}
}

//繼承EventArgs
class myEvenArg : EventArgs
{
public string msg { get; private set; }
public myEvenArg(string msg)
{
this.msg = msg;
}
}

也可以自行定義delegate去做
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

//建立測試按鈕事件
private void button1_Click(object sender, EventArgs e)
{
ukhs obj = new ukhs();

//加入訂閱事件
obj.newEvent += new ukhs.myEvent(obj_newEvent);

//測試
obj.goFire();
}

string obj_newEvent(string msg)
{
MessageBox.Show(msg);
return "我已經完成任務了";
}
}
}

//自行寫的class
class ukhs
{
//宣到一個delegate
public delegate string myEvent(string msg);
public event myEvent newEvent;
public void goFire()
{
//判斷是否有人訂閱
if (newEvent != null)
{
//執行delegate
string getMsg = newEvent("發射飛彈!!");
MessageBox.Show(getMsg);
}
}
}

有問題在一起討論ㄅ..

2 則留言:

昊玥 提到...

請問大大~在VS2005的環境下自訂元件項裡面加一個自訂一個EVENT是否在,其他地方加入該自訂元件時無法在Reference屬性表中看見該EVENT(閃電符號)

Bibby 提到...

寫控制項,我比較不熟,我都寫自己用的,所以沒有管這麼多^^||