Deck.P​​rint仅显示2张黑桃已添加到牌组列表中

时间:2018-09-25 05:37:09

标签: c# playing-cards

因此,正如这个问题的标题所说,我的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);
    }
}

1 个答案:

答案 0 :(得分:3)

因此,您的问题是,您正在使用Print方法读取(可能是) 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);
    }
}