計算機科学のブログ

enums and collections - Organizing your data - enum, int

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 8(enums and collections - Organizing your data)、p.409(Exercise)の解答を求めてみる。

コード

Suits.cs

using System;
namespace MyFirstConsoleApp
{
    public enum Suits
    {
        Diamonds,
        Clubs,
        Hearts,
        Spades,
    }
}

コード

Values.cs

using System;
namespace MyFirstConsoleApp
{
    public enum Values
    {
        Ace = 1,
        Two,
        Three,
        Four,
        Five,
        Six,
        Seven,
        Eight,
        Nine,
        Ten,
        Jack,
        Queen,
        King,
    }
}

コード

Card.cs

using System;
namespace MyFirstConsoleApp
{
    public class Card
    {
        public Suits Suit { get; private set; }
        public Values Value { get; private set; }
        public string Name => $"{Value} of {Suit}";

        public Card(Values value, Suits suit)
        {
            Suit = suit;
            Value = value;
        }
    }
}

コード

Program.cs

using System;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Card card = new Card(Values.Ace, Suits.Spades);
            Console.WriteLine(card.Name);
            Random random = new Random();

            for (int i = 0; i < 10; i++)
            {
                card = new Card((Values)random.Next(1, 14), (Suits)random.Next(4));
                Console.WriteLine(card.Name);
            }
        }
    }
}

入出力結果(Terminal, Zsh)

Ace of Spades
Six of Hearts
Jack of Clubs
Three of Spades
Three of Clubs
Five of Spades
Eight of Hearts
Four of Clubs
Jack of Hearts
Ace of Diamonds
Four of Diamonds