如何将int转换为枚举值?

时间:2013-08-02 05:29:55

标签: c# class

这是我的代码,它会抛出错误Cannot convert type "int" to Cards.Suits和。{ Cannot 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;
}

现在,套装enum和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 个答案:

答案 0 :(得分:2)

根据你的枚举声明,Suit在[0..3]范围内,而rank在[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]
    ...

答案 1 :(得分: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;
}

答案 2 :(得分:0)

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

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

答案 3 :(得分: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