如何将int转换为枚举值?

这个问题在这里已经有了答案:

  • 在int C中枚举21枚答案

  • 根据你的枚举声明,Suit在[0..3]范围内,而等级在[1..13]范围内(注意,该等级不是以0为基础的),所以应该纠正内循环:

      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]
        ...
    

    像这样改变你的路线

     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;
    }
    

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

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

    链接地址: http://www.djcxy.com/p/22515.html

    上一篇: How to convert int to enum value?

    下一篇: Can you call an Enum by the number value?