計算機科学のブログ

enums and collections - Organizing your data - Enums, cast

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 8(enums and collections - Organizing your data)、p.409(Exercise)の解答を求めてみる。

コード

Program.cs

using System.Runtime.CompilerServices;
using ConsoleApp1;

Card myCard = new Card(Values.Ace, Suits.Spades);
Console.WriteLine(myCard.Name);

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

Card.cs

using System;

namespace ConsoleApp1;

public class Card
{
    public Values Value { get; }
    public Suits Suit { get; }
    public string Name
    {
        get { return $"{Value} of {Suit}"; }
    }

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

Suits.cs

namespace ConsoleApp1;

public enum Suits
{
    Diamonds,
    Clubs,
    Hearts,
    Spades,
}

Values.cs

namespace ConsoleApp1;

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

入出力結果(Terminal, Zsh)

% dotnet run
Ace of Spades
Five of Spades
Four of Hearts
Jack of Clubs
Ace of Diamonds
Queen of Diamonds
Queen of Spades
Two of Hearts
Jack of Spades
Six of Spades
Jack of Spades
King of Diamonds
King of Diamonds
Five of Hearts
Ten of Hearts
King of Clubs
Eight of Clubs
Ace of Hearts
Seven of Diamonds
Six of Spades
Queen of Spades
%