學習重點
- 欄位的屬性
- 類別建構子
- ToString()方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Party_Planer
{
public partial class Form1 : Form
{
DinnerParty dinnerparty;//宣告dinnerparty是一個DinnerParty的變數。
public Form1()
{
InitializeComponent();
dinnerparty = new DinnerParty(5, false, true);
//設定dinnerparty是DinnerParty裡的一個物件,呼叫DinnerParty的建構子並給予初始值。
DisplayDinnerPartyCost();
}
private void DisplayDinnerPartyCost()
{
decimal Cost = dinnerparty.CalculateCost(healthyBox.Checked);
CostLabel.Text = Cost.ToString("c");
//ToString()方法可以將任何的變數轉換成字串,
//但假如你傳送"c"給ToString(),它會將值轉換成當地貨幣,在此轉換成台幣。
}
private void fancyBox_CheckedChanged(object sender, EventArgs e)
{
dinnerparty.CalculateCostOfDecorations(fancyBox.Checked);
DisplayDinnerPartyCost();
}
private void healthyBox_CheckedChanged(object sender, EventArgs e)
{
dinnerparty.SetHealthyOption(healthyBox.Checked);
DisplayDinnerPartyCost();
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
dinnerparty.NumberOfPeople = (int)numericUpDown1.Value;
//呼叫NumberOfPeople的set存取器。
DisplayDinnerPartyCost();
}
}
}
副程式碼(DinnerParty類別)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Party_Planer
{
public class DinnerParty
{
public const int CostOfFoodPerPerson = 25;
private int numberOfPeopele = 5;
//使用numberOfPeople的屬性。
public int NumberOfPeople
{
get//當numberOfPeople欄位被讀取時所使用的方法。
{
return numberOfPeopele;
}
set//當numberOfPeople欄位被設定時所使用的方法。
{
numberOfPeopele = value;
CalculateCostOfDecorations(fancyDecorations);
}
}
private bool fancyDecorations;
public decimal CostOfBeveragesPerPerson;
public decimal CostOfDecorations = 0;
//為DinnerParty類別增加建構子初始化私有欄位。
public DinnerParty(int numberOfPeople, bool healthyOption, bool fancyDecorations)
{
NumberOfPeople = numberOfPeopele;//觸發NumberOfPeople屬性的set方法。
this.fancyDecorations = fancyDecorations;
//等號左邊的this.fancyDecorations指的是DinnerParty類別裡面的fancyDecoration欄位,
//而等號右邊的fancyDecorations在這邊代表DinnerParty建構子裡面的參數。
SetHealthyOption(healthyOption);
CalculateCostOfDecorations(fancyDecorations);
}
public void SetHealthyOption(bool healthyOption)
{
if(healthyOption)
{
CostOfBeveragesPerPerson = 5.00M;
}
else
{
CostOfBeveragesPerPerson = 20.00M;
}
}
public void CalculateCostOfDecorations(bool fancy)
{
fancyDecorations = fancy;
if(fancy)
{
CostOfDecorations = (NumberOfPeople * 15.00M) + 50M;
//呼叫NumberOfPeople的get存取器。
}
else
{
CostOfDecorations = (NumberOfPeople * 7.50M) + 30M;
//呼叫NumberOfPeople的get存取器。
}
}
public decimal CalculateCost(bool healthyOption)
{
decimal totalCost = CostOfDecorations + ((CostOfBeveragesPerPerson + CostOfFoodPerPerson) * NumberOfPeople);
//呼叫NumberOfPeople的get存取器。
if (healthyOption)
{
return totalCost * .95M;
}
else
{
return totalCost;
}
}
}
}
Demo圖
一開始執行時的畫面
人數增為10人
勾選Healthy Option
取消Fancy decorations
沒有留言:
張貼留言