Re: [問題] delegate & event

作者: fo40225   2015-08-09 10:44:43
※ 引述《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;
}
}

Links booklink

Contact Us: admin [ a t ] ucptt.com