計算機科学のブログ

interfaces, casting, and "is" - Making classes keep their promises - cast, is, as, null

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 7(interfaces, casting, and “is” - Making classes keep their promises)、p.389(Exercise)の解答を求めてみる。

コード

IClown.cs

using System;
namespace MyFirstConsoleApp
{
    public interface IClown
    {
        string FunnyThingIHave { get; }
        void Honk();
    }
}

コード

IScaryClown.cs

using System;
namespace MyFirstConsoleApp
{
    public interface IScaryClown:IClown
    {
        string ScaryThingIHave { get; }
        void ScareLittleChildren();
    }
}

コード

FunnyFunny.cs

using System;
namespace MyFirstConsoleApp
{
    public class FunnyFunny:IClown
    {
        private string funnyThingIHave;
        public FunnyFunny(string funnyThingIHave)
        {
            this.funnyThingIHave = funnyThingIHave;
        }

        public string FunnyThingIHave => funnyThingIHave;

        public void Honk()
        {
            Console.WriteLine($"Hi kids! I have a {funnyThingIHave}.");
        }
    }
}

コード

ScaryScary.cs

using System;
namespace MyFirstConsoleApp
{
    public class ScaryScary:FunnyFunny, IScaryClown
    {
        private int scaryThingCount;
        public ScaryScary(string funnyThingIHave, int scaryThingCount)
            :base(funnyThingIHave)
        {
            this.scaryThingCount = scaryThingCount;
        }

        public string ScaryThingIHave => $"{scaryThingCount} spiders";

        public void ScareLittleChildren()
        {
            Console.WriteLine($"Boo! Gotcha! Look at my {ScaryThingIHave}!");
        }
    }
}

コード

Program.cs

using System;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            IClown fingersTheClown = new ScaryScary("big red nose", 14);
            fingersTheClown.Honk();
            if (fingersTheClown is IScaryClown scaryClown)
            {
                scaryClown.ScareLittleChildren();
            }
            IScaryClown scaryClown1 = fingersTheClown as IScaryClown;
            if (scaryClown1 != null)
            {
                scaryClown1.ScareLittleChildren();
            }
        }
    }
}

入出力結果(Terminal, Zsh)

Hi kids! I have a big red nose.
Boo! Gotcha! Look at my 14 spiders!
Boo! Gotcha! Look at my 14 spiders!