Head First C#
頭とからだで覚えるC#の基本
(オライリージャパン)
Andrew Stellman (著), Jennifer Green (著)
佐藤 嘉一 (監修), 木下 哲也 (翻訳)
開発環境
- Microsoft Windows 8.1 Pro (VMware Fusion 6, OS X Mavericks - Apple) (OS)
- C# (プログラミング言語)
- Microsoft Visual Studio Express 2013 for Windows Desktop (統合開発環境, IDE)
Head First C#―頭とからだで覚えるC#の基本 (Andrew Stellman (著)、Jennifer Green (著)、佐藤 嘉一 (監修)、木下 哲也 (翻訳)、オライリージャパン)の5章(継承: オブジェクトの系図)、エクササイズ(p.204)を解いてみる。
エクササイズ(p.204)
コード
Form1.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class Party
{
const decimal costOfFoodPerPerson = 2500;
public int numberOfPeople;
public decimal costOfDecorations;
public Party(int numberOfPeople, bool decoration)
{
this.numberOfPeople = numberOfPeople;
CalculateCostOfDecoration(decoration);
}
public int NumberOfPeople
{
get { return numberOfPeople; }
set { numberOfPeople = value; }
}
public void CalculateCostOfDecoration(bool decoration)
{
if (decoration)
{
costOfDecorations = 1500M * numberOfPeople + 5000M;
}
else
{
costOfDecorations = 750M * numberOfPeople + 3000M;
}
}
public virtual decimal CalculateCost()
{
return costOfFoodPerPerson * numberOfPeople + costOfDecorations;
}
}
public class DinnerPary : Party
{
decimal costOfbeveragesPerPerson;
bool healthyOption;
public DinnerPary(int numberOfPeople, bool decoration, bool healthyOption)
: base(numberOfPeople, decoration)
{
this.healthyOption = healthyOption;
this.costOfbeveragesPerPerson = healthyOption ? 500M : 2000M;
}
public override decimal CalculateCost()
{
decimal cost = base.CalculateCost() + costOfbeveragesPerPerson * numberOfPeople;
cost = healthyOption ? cost * 0.95M : cost;
return cost; ;
}
}
public class BirthdayParty : Party
{
int cakeSize;
string cakeWriging;
public BirthdayParty(int numberOfPeople, bool decoration, string cakeWriging)
: base(numberOfPeople, decoration)
{
CalculateCakeSize();
this.cakeWriging = cakeWriging;
}
void CalculateCakeSize()
{
if (NumberOfPeople <= 4)
{
cakeSize = 7;
}
else
{
cakeSize = 15;
}
}
public string CakeWriging
{
get { return this.cakeWriging; }
set
{
int maxLength;
if (cakeSize == 7)
{
maxLength = 16;
}
else
{
maxLength = 40;
}
if (value.Length > maxLength)
{
MessageBox.Show(cakeSize + "号のケーキには文字数が多すぎます");
if (maxLength > cakeWriging.Length)
{
maxLength = cakeWriging.Length;
}
this.cakeWriging = cakeWriging.Substring(0, maxLength);
}
else
{
this.cakeWriging = value;
}
}
}
public override decimal CalculateCost()
{
decimal cost = base.CalculateCost() + 25 * cakeWriging.Length;
if (numberOfPeople > 12)
{
cost += 10000;
}
return cost;
}
}
}
0 コメント:
コメントを投稿