Re: [問題] delegate & event
※ 引述《jodo1984 (XDDD)》之銘言:
自己寫了一個範例給您參考 看不懂的地方都可以問
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//這是區域變數
var Benz = new Car() { Name = "Benz" };
Benz.TooFast += TooFast;
Benz.TooSlow += TooSlow;
Benz.Speed = 22;
MessageBox.Show(
string.Format(
"汽車智慧系統自動調速至{0}!!",
Benz.Speed));
}
private void TooFast(object o, SpeedEventArgs e)
{
var car = o as Car;
if (car != null)
{
MessageBox.Show(
string.Format(
"{0}目前的速度為{1},超過200,請減速慢行",
car.Name,
car.Speed));
}
}
private void TooSlow(object o, SpeedEventArgs e)
{
var car = o as Car;
if (car != null)
{
MessageBox.Show(
string.Format(
"{0}目前行駛速度{1},已低於限速80,請加速行駛",
car.Name,
car.Speed));
}
}
}
public class Car
{
public string Name { get; set; }
//這是實體欄位(變數)
private int _speed;
//這是實體屬性(方法)
public int Speed
{
get
{
return this._speed;
}
set
{
if (value > 200)
{
this.OnTooFast(new SpeedEventArgs(value));
value = 200;
}
if (value < 80)
{
this.OnTooSlow(new SpeedEventArgs(value));
value = 80;
}
this._speed = value;
}
}
private EventHandler<SpeedEventArgs> _tooFastHandler;
public event EventHandler<SpeedEventArgs> TooFast
{
add
{
this._tooFastHandler += value;
}
remove
{
this._tooFastHandler -= value;
}
}
protected virtual void OnTooFast(SpeedEventArgs e)
{
//執行緒安全的寫法
EventHandler<SpeedEventArgs> handler =
Interlocked.CompareExchange(
ref this._tooFastHandler, null, null);
if (handler != null)
{
handler(this, e);
}
}
private EventHandler<SpeedEventArgs> _tooSlowHandler;
public event EventHandler<SpeedEventArgs> TooSlow
{
add
{
this._tooSlowHandler += value;
}
remove
{
this._tooSlowHandler -= value;
}
}
protected virtual void OnTooSlow(SpeedEventArgs e)
{
EventHandler<SpeedEventArgs> handler =
Interlocked.CompareExchange(
ref this._tooSlowHandler, null, null);
if (handler != null)
{
handler(this, e);
}
}
}
[Serializable]
public class SpeedEventArgs : EventArgs
{
public SpeedEventArgs(int speed)
{
this.Speed = speed;
}
public int Speed
{
get;
private set;
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.169.201.114
※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1439088287.A.A96.html
※ 編輯: fo40225 (1.169.201.114), 08/09/2015 11:04:02
討論串 (同標題文章)
完整討論串 (本文為第 2 之 3 篇):
C_Sharp 近期熱門文章
PTT數位生活區 即時熱門文章