2010年4月5日 星期一

[c#] 事件1Car 應用介紹-[Event 1Car]

事件 應用介紹-[Event]

//Car 事件類別
namespace even_car
{
//事件委派
delegate void DangerEvent(int Speed);

class Car
{
private int m_speed;

//宣告事件
public event DangerEvent Danger;

public int Speed
{
get
{
return m_speed;
}
set
{
if (value >200)
if (Danger != null)
{
Danger(value);
}

m_speed = value;
}
}
}
}

//測試程式
namespace even_car
{
class Program
{
static void Main(string[] args)
{
test事件();
Console.ReadLine();
}

static void test事件()
{
Car Benz = new Car();
//指定Danger事件由ToolFast方法來處理
Benz.Danger += new DangerEvent(ToolFast);
//車子速度屬性指定
Benz.Speed = 300;
}


static void ToolFast(int vSpeed)
{
Console.WriteLine("目前的速度{0},高過200,請減速!!", vSpeed);
}
}
}

沒有留言:

張貼留言