encapsulation - Keep your privates… private - fields, properties, getter, setter
Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 5(encapsulation - Keep your privates… private)、p.267(Exercise)の解答を求めてみる。
コード
SwordDamage.cs
using System;
namespace BlazorSwordDamage
{
public class SwordDamage
{
private const int BASE_DAMAGE = 3;
private const int FLAME_DAMAGE = 2;
private int roll;
private bool flaming;
private bool magic;
public int Roll
{
get { return roll; }
set
{
roll = value;
CalculateDamage();
}
}
public bool Flaming
{
get { return flaming; }
set
{
flaming = value;
CalculateDamage();
}
}
public bool Magic
{
get { return magic; }
set
{
magic = value;
CalculateDamage();
}
}
public int Damage { get; private set; }
public SwordDamage(int roll)
{
this.roll = roll;
CalculateDamage();
}
private void CalculateDamage()
{
decimal magicMultiplier = 1M;
if (Magic)
{
magicMultiplier = 1.75M;
}
Damage = BASE_DAMAGE + (int)(Roll * magicMultiplier);
if (Flaming)
{
Damage += FLAME_DAMAGE;
}
}
}
}
コード
index.razor
@page "/"
<div class="container">
<div class="row justify-content-center">
<div class="col-3 text-left">
<input class="form-check-input" type="checkbox" id="flaming"
@bind="swordDamage.Flaming"/>
<label class="form-check-label" for="flaming">
Flaming
</label>
</div>
<div class="col-3 text-right">
<input class="form-check-input" type="checkbox" id="magic"
@bind="swordDamage.Magic"/>
<label class="form-check-label" for="magic">
Magic
</label>
</div>
</div>
<div class="row justify-content-center mt-5">
<div class="col-4 text-center">
<button class="btn btn-primary"
@onclick="RollDice">
Roll for damage
</button>
</div>
</div>
<div class="row justify-content-center mt-5">
<div class="col-6 text-center">
<h3>Rolled @swordDamage.Roll for @swordDamage.Damage HP</h3>
</div>
</div>
</div>
@code {
Random random = new Random();
SwordDamage swordDamage = new SwordDamage(10);
string damageText = "";
protected override void OnInitialized()
{
RollDice();
}
public void RollDice()
{
swordDamage.Roll = 0;
for (int i = 0; i < 3; i++)
{
swordDamage.Roll += random.Next(1, 7);
}
}
}