How to enumerate an enum

后端 未结 29 1839
深忆病人
深忆病人 2020-11-22 01:14

How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{         


        
29条回答
  •  不思量自难忘°
    2020-11-22 01:39

    This question appears in Chapter 10 of "C# Step by Step 2013"

    The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):

    class Pack
    {
        public const int NumSuits = 4;
        public const int CardsPerSuit = 13;
        private PlayingCard[,] cardPack;
    
        public Pack()
        {
            this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
            for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
            {
                for (Value value = Value.Two; value <= Value.Ace; value++)
                {
                    cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
                }
            }
        }
    }
    

    In this case, Suit and Value are both enumerations:

    enum Suit { Clubs, Diamonds, Hearts, Spades }
    enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}
    

    and PlayingCard is a card object with a defined Suit and Value:

    class PlayingCard
    {
        private readonly Suit suit;
        private readonly Value value;
    
        public PlayingCard(Suit s, Value v)
        {
            this.suit = s;
            this.value = v;
        }
    }
    

提交回复
热议问题