計算機科学のブログ

Interfaces, casting, and is: Making classes keep their promises - Interface inferitance

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

コード

Program.cs

IClown fingersTheClown = new ScaryScary("big red nose", 14);
fingersTheClown.Honk();
// Hi kids! I have a big red nose.
// IScaryClown iScaryClownReference = fingersTheClown;
if (fingersTheClown is IScaryClown iScaryClownReference)
{
    iScaryClownReference.ScareLittleChildren();
}
// Boo! Gotcha! Look at my 14 spiders!
interface IClown
{
    string FunnyThingIHave { get; }
    void Honk();
}
interface IScaryClown : IClown
{
    string ScaryThingIHave { get; }
    void ScareLittleChildren();
}
class FunnyFunny : IClown
{
    private string funnyThingIHave;
    public string FunnyThingIHave
    {
        get { return funnyThingIHave; }
    }
    public void Honk()
    {
        Console.WriteLine($"Hi kids! I have a {funnyThingIHave}.");
    }
    public FunnyFunny(string funnyThingIHave)
    {
        this.funnyThingIHave = funnyThingIHave;
    }
}
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}!");
    }
}

入出力結果(Terminal, Zsh)

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