Deck.Print 仅显示 2 个黑桃已添加到套牌列表中

Deck.Print is only showing 2 of spades have been added to deck list

所以正如这个问题的标题所说,我的Deck.Print()只显示黑桃2已被添加。

我的理论是,出于某种原因,在 Deck() 中创建的纸牌没有改变纸牌的花色和正面,因此它们坚持枚举的默认值(我假设默认值是什么在枚举中为 0)。

从我的角度来看,它应该是创建卡片,将 Enum 类型投射到 I 或 F,然后将该卡片添加到 deck.list。为什么这不起作用?谢谢

class Deck
{
    public List<Card> cards = new List<Card>();

    public Deck() // Generates all cards in the deck
    {
        for (int i = 0; i < 4; i++)
        {
            for (int f = 0; f < 13; f++)
            {
                Card card = new Card();
                card.Suit = (Suit)i;
                card.Face = (Face)f;
                cards.Add(card);
            }
        }
    }

    public void Print() // prints all cards in the deck , used for testing
    {
        foreach (var card in cards)
        {
            card.Print();
        }
    }
}
enum Suit
{
    Spades,
    Hearts,
    Diamonds,
    Clovers
}

enum Face
{
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
    Ace
}

class Card
{
    private Suit suit;
    private Face face;

    public Suit Suit { get; set; }
    public Face Face { get; set; }

    public void Print()
    {
        Console.WriteLine("{0} of {1}", face, suit);
    }
}

因此,您的问题是,您在 Print 方法中阅读 originally/suspiciously 类似于 Backing Fields 的内容,而这又从未被设置过。

如果您不需要这些字段,只需像您一样使用 Auto Properties,并删除它们以减少混乱

public Suit Suit { get; set; }

已修改

class Card
{
    // jsut delete these all together
    //private Suit suit; // you are printing this out and never changing it
    //private Face face; // you are printing this out and never changing it

    public Suit Suit { get; set; }
    public Face Face { get; set; }

    public void Print()
    {
      //  Console.WriteLine("{0} of {1}", face, suit);
      // print your actual properties not the backing fields that have never been set
      Console.WriteLine("{0} of {1}", Face, Suit);
    }
}