計算機科学のブログ

encapsulation - Keep your privates...private - this keyword

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 5(encapsulation - Keep your privates…private)、p.265(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs

GumballMachine gumballMachine = new GumballMachine(5, 10);

Console.WriteLine($"Price: {gumballMachine.Price}");
int[] ints = [5, 10, 15];
foreach (int coinsInserted in ints)
{
    Console.WriteLine(gumballMachine.DispencseOneGumball(coinsInserted));
}
internal class GumballMachine
{
    private int gumballs;
    private int price;
    public int Price { get { return price; } }
    public GumballMachine(int gumballs, int price)
    {
        this.gumballs = gumballs;
        this.price = price;
    }
    public string DispencseOneGumball(int coinsInserted)
    {
        Console.WriteLine($"gumballs: {gumballs}");
        if (coinsInserted >= price)
        {
            gumballs -= 1;
            return "Here's your gumbaln";
        }
        return "Insert more coins";
    }
}

入出力結果(Terminal, Zsh)

% dotnet run
Price: 10
gumballs: 5
Insert more coins
gumballs: 5
Here's your gumbaln
gumballs: 4
Here's your gumbaln
%