我想创建枚举类型:
enum Ranks{ 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace}
有什么办法吗?
答案 0 :(得分:0)
似乎没有优雅的方法可以做到这一点,所以这是一个黑客:在每个整数的开头附加一个下划线!
enum LikeThis { _1, _2, _3, _4, _5, _6 }
答案 1 :(得分:0)
简短回答:否
常规答案:只需使用字符并获取如下数值:
int numericValueOne = (int)Value.Ace;
int numericValueTwo = (int)Value.Two;
答案很长:如果最终用法是一副牌,这是一个很好的实现:
public class Card
{
private readonly Suit _suit;
private readonly Value _value;
public Card(int number)
{
_suit = (Suit)(number / 13); // 0 = Hearts, 1 = Diamonds ...
_value = (Value)(number % 13 + 1); // 1 = ace, 2 = two
}
public Suit Suit
{
get { return _suit; }
}
public Value Value
{
get { return _value; }
}
public int ToNumber()
{
return (int)_suit * 13 + ((int)_value - 1);
}
}
public enum Suit
{
Hearts = 0,
Diamonds = 1,
Clubs = 2,
Spades = 3
}
public enum Value
{
Ace = 1,
Two = 2,
Three = 3,
Four = 4,
Five = 5,
Six = 6,
Seven = 7,
Eight = 8,
Nine = 9,
Ten = 10,
Jack = 11,
Queen = 12,
King = 13,
}
将这两个枚举包装在此类中的好处是您可以将每张卡用作数字(0-52)和/或类。此外,您可以根据需要向类添加任何操作,方法和属性,当您存储或传输数据时,只需使用数字。 Ref
答案 2 :(得分:0)
你可以这样做:
enum Ranks { Ace = 'A', Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten, King = 'K', Queen = 'Q', Jack = 'J' };
然后按如下方式对Rank进行切换:
switch (Rank)
{
case Ranks.Two:
case Ranks.Three:
case Ranks.Four:
// Cast to an int and display it
break;
case Ranks.Ace:
case Ranks.King:
case Ranks.Queen:
case Ranks.King:
// Cast to char and display it
break;
}
我在一个简单的二十一点游戏中使用了这个,我写的很好,