How to convert int to enum value?
本问题已经有最佳答案,请猛点这里访问。
这是我的代码,它在说
1 2 3 4 5 6 7 8 9 10 11 12 |
卡构造者是
1 2 3 4 5 6 7 | public readonly Suits suit; public readonly Rank rank; public Card(Suits newSuit, Rank newRank) { suit = newSuit; rank = newRank; } |
现在西服枚举和等级枚举是从ace=1开始的普通牌组,所以西服是钻石、梅花、红心、黑桃。有人能告诉我为什么会出现上述错误吗?以下代码取自一本书。谢谢!
*编辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public enum ranks { ACE = 1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, } public enum Suit { DIAMOND, CLUB, HEART, SPADE, } |
根据枚举声明,suit在[0..3]范围内,而ranks在[1..13]范围内(请注意,ranks不是基于零的),因此应更正内部for循环:
1 2 3 4 | 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 2 3 4 5 6 7 | public readonly Suit suit; public readonly ranks rank; public Card(Suit newSuit, ranks newRank) { suit = newSuit; rank = newRank; } |
这个运行得很好但是纠正这个
1 2 3 4 5 6 7 | 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); } } |
在这里
in cards[suitVal * 13 + rankVal - 1]
1 2 3 | [Loop 1:] suitVal =0 rankVal=0 |
[suitVal * 13 + rankVal - 1]= [0*13+0-1]= [-1] ! oops!
在您的prgm中:
1 2 | public readonly Suit suit; //not Suits public readonly ranks rank; //not Rank |
我会看到它会得到其他错误"索引在数组的边界之外"
当suiteval=0和rankval=0时,卡片[suiteval*13+rankval-1]=-1,它在数组索引之外。