2010年4月5日 星期一

[c#] 事件2Human 應用介紹-[Event 2Human ]

事件 應用介紹-[Event]

//人員 事件類別
namespace even_tst
{
delegate void weightEvent(int weight);

class Human
{
private int 身高;
private int 體重;
public static int 人數;

public event weightEvent Wei;

public Human()
{
身高 = 180;
體重 = 65;
人數++;
}
public Human(int 身高,int 體重)
{
this.身高 = 身高;
this.體重 = 體重;
人數++;
}


//存取子方式-設定重量並判斷
public int Weight
{
get
{
return 體重;
}
set
{
if (value > 100)
if (Wei != null)
Wei(value);

體重 = value;

}

}

public void 秀身高體重()
{
Console.WriteLine("身高={0},體重={1},人數={2}", 身高, 體重, 人數);

}

//設定重量並判斷
public void set體重(int x)
{
if (x> 100)
if (Wei != null)
Wei(x);

體重 = x;
}

}
}

///////////////////
//測試程式
//////////////////

namespace even_tst
{
class Program
{

static void Main(string[] args)
{
test事件1();
Console.ReadLine();
}

//
public static void test事件1()
{
Human p1 = new Human();

//指定 Danger事件由 TooFast方法來處理

p1.Wei += new weightEvent(Too胖);

p1.set體重(150);
p1.Weight = 200;
}

static void Too胖(int x)
{
Console.WriteLine("目前的體重 {0},超過 100,請減肥!!!", x);
}
}
}

沒有留言:

張貼留言