11

这是我的代码,它抛出一个错误说Cannot convert type "int" to Cards.SuitsCannot convert type "int" to Cards.Rank

private Card[] cards;
public Deck()
{
    cards = new Card[52];
    for (int suitVal = 0; suitVal < 4; suitVal++)
    {
        for (int rankVal = 0; rankVal < 14; rankVal++)
        {
            cards[suitVal * 13 + rankVal - 1] = new Card((Suits)suitVal, (Rank)rankVal);
        }
     }
}

卡片构造函数是

public readonly Suits suit;
public readonly Rank rank;
public Card(Suits newSuit, Rank newRank)
{
    suit = newSuit;
    rank = newRank;
}

现在 Suits 枚举和 Rank 枚举是从 ACE = 1 开始的常规牌组,以此类推,花色是 DIAMONDS、CLUBS、HEARTS、SPADES。谁能告诉我为什么我得到上述错误。以下代码取自一本书。谢谢!

*编辑

    public enum ranks
    {
        ACE = 1,
        TWO,
        THREE,
        FOUR,
        FIVE,
        SIX,
        SEVEN,
        EIGHT,
        NINE,
        TEN,
        JACK,
        QUEEN,
        KING,
    }

    public enum Suit
    {
        DIAMOND,
        CLUB,
        HEART,
        SPADE,
    }
4

4 回答 4

2

根据您的枚举声明,Suit 在 [0..3] 范围内,而排名在 [1..13] 范围内(注意,排名不是从零开始的),因此应更正内部 for 循环:

  for (int rankVal = 0; rankVal < 13; rankVal++) // <- 14 changed for 13: [0..13] has the same length as [1..14] 
  { 
    cards[suitVal * 13 + rankVal] = new Card((Suits)suitVal, (Rank)(rankVal + 1)); // <- removed -1 from index; add 1 to rankVal, we need [1..14], not [0..13]
    ...
于 2013-08-02T05:59:12.150 回答
1

像这样改变你的线路

 cards[suitVal * 13 + rankVal] = new Card(((Suit)suitVal), ((ranks)rankVal));

并且由于您的类在构造函数中使用枚举,所以像这样更改它

public readonly Suit suit;
public readonly ranks rank;
public Card(Suit newSuit, ranks newRank)
{
    suit = newSuit;
    rank = newRank;
}
于 2013-08-02T05:46:55.157 回答
0

这运行良好,但纠正这个

    for (int suitVal = 0; suitVal < 4; suitVal++)
    {
        for (int rankVal = 0; rankVal < 14; rankVal++)
        {
            cards[suitVal * 13 + rankVal - 1] = new Card((Suit)suitVal, (Rank)rankVal);
        }
    }

这里

在卡[suitVal * 13 + rankVal - 1]

[Loop 1:]
suitVal =0
rankVal=0

[suitVal * 13 + rankVal - 1]= [0*13+0-1]= [-1] !哎呀!

并在您的 prgm 中:

public readonly Suit  suit; //not Suits
public readonly ranks rank; //not Rank 
于 2013-08-02T10:41:56.947 回答
0

我会看到它会得到其他错误“索引超出了数组的范围”

当 suitVal = 0 且 rankVal = 0 时,cards[suitVal * 13 + rankVal - 1] =-1,它在数组索引之外。

于 2013-08-02T06:06:36.940 回答