計算機科学のブログ

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

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.367(Pool Puzzle)の解答を求めてみる。

コード

Program.cs

string result = "";
INose[] i = { new Acts(), new Clowns(), new Of2016() };
foreach (INose item in i)
{
    result += $"{item.Ear()} {item.Face}\n";
}
Console.WriteLine(result);

interface INose
{
    public int Ear();
    string Face { get; }
}
abstract class Picasso : INose
{
    private string face;

    public virtual string Face => face;
    public abstract int Ear();
    public Picasso(string face)
    {
        this.face = face;
    }
}
class Clowns : Picasso
{
    public override int Ear()
    {
        return 7;
    }
    public Clowns() : base("Clowns") { }
}
class Acts : Picasso
{
    public override int Ear()
    {
        return 5;
    }
    public Acts() : base("Acts") { }
}
class Of2016 : Clowns
{
    public override string Face => "Of2016";
}

入出力結果(Terminal, Zsh)

% dotnet run
5 Acts
7 Clowns
7 Of2016

%