學習重點:
- 使用OOP方式將資料包裝在一起
- 類別內的方法可以互相呼叫
主程式 :
private void button1_Click(object sender, EventArgs e)
{
M = new Person(textBox_M.Text,
0);
F = new Person(textBox_F.Text,
20000);
label_MName.Text = M.Name;
label_FName.Text = F.Name;
button2.Text = "跟"+ F.Name + "借1000元";
button3.Text = "還給" + F.Name + "1000元";
textBox_M.Enabled = false;
textBox_F.Enabled = false;
button1.Enabled
= false;
button2.Enabled = true;
button3.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
M.borrow(F, 1000);
UpdateMoney();
}
private void button3_Click(object sender, EventArgs e)
{
M.repay(F, 1000);
UpdateMoney();
}
private void UpdateMoney()
{
label_MMoney.Text = M.Money.ToString();
label_FMoney.Text = F.Money.ToString();
}
Person 類別 :
class Person
{
public string Name;
public int Money;
public Person(string name, int money)
{
this.Name = name;
this.Money = money;
}
public void borrow(Person lender, int money)
{
if(lender.Money >= money)
{
lender.Money -= money;
this.Money += money;
}
}
public void repay(Person lender, int money)
{
if (this.Money
>= money)
{
this.Money -= money;
lender.Money += money;
}
}
}
沒有留言:
張貼留言