計算機科学のブログ

inheritance - Your object's family tree - abstract class, abstract method

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 6(inheritance - Your object’s family tree)、p.339(Exercise)の解答を求めてみる。

コード

WeaponDamage.cs

using System;
namespace MyFirstConsoleApp
{
    public abstract class WeaponDamage
    {
        private int roll;
        public int Roll
        {
            get { return roll; }
            set
            {
                roll = value;
                CalculateDamage();
            }
        }
        private bool magic;
        public bool Magic
        {
            get
            {
                return magic;
            }
            set
            {
                magic = value;
                CalculateDamage();
            }
        }
        private bool flaming;
        public bool Flaming
        {
            get
            {
                return flaming;
            }
            set
            {
                flaming = value;
                CalculateDamage();
            }
        }
        public int Damage { get; protected set; }

        public WeaponDamage(int roll)
        {
            Roll = roll;
            CalculateDamage();
        }
        protected abstract void CalculateDamage();
    }
}

入出力結果(Terminal, Zsh)


S for sword, A for Arrow, anything else to quit: S
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 0
Rolled 8 for 11 HP

S for sword, A for Arrow, anything else to quit: S
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 2
Rolled 14 for 19 HP

S for sword, A for Arrow, anything else to quit: S
0 for no magic/flaming, 1 for magic, 2 for flaming, 3 for both: 3
Rolled 9 for 20 HP

S for sword, A for Arrow, anything else to quit: q