我制作了以下代码,使用2个枚举和一个switch语句创建一副牌。我不认为switch语句是一个优雅的解决方案。因此,我的问题是:是否可以通过循环枚举来避免switch语句?
变量Value31用于存储卡片在" 31"游戏中的值。
namespace CardGame31
{
public enum SuitPossibleValues { Clubs, Diamonds, Hearts, Spades };
public enum RankPossibleValues { two, three, four, five, six, seven, eight, nine, ten, Jack, Queen, King, Ace };
class Program
{
static void Main(string[] args)
{
CardDeck myCardDeck = new CardDeck();
}
}
class CardDeck
{
List<Card> CardDeckList = new List<Card>();
public CardDeck()
{
foreach (SuitPossibleValues colourPossibleValues in Enum.GetValues(typeof(SuitPossibleValues)))
{
foreach (RankPossibleValues namePossibleValues in Enum.GetValues(typeof(RankPossibleValues)))
{
Card nextCard = new Card(colourPossibleValues.ToString(), namePossibleValues.ToString());
CardDeckList.Add(nextCard);
}
}
}
}
class Card
{
public string Colour { get; }
public string Name { get; }
public int Value31 { get; }
public Card(string colour, string name)
{
Colour = colour;
Name = name;
switch (name)
{
case ("two"):
Value31 = 2;
break;
case ("three"):
Value31 = 3;
break;
case ("four"):
Value31 = 4;
break;
case ("five"):
Value31 = 5;
break;
case ("six"):
Value31 = 6;
break;
case ("seven"):
Value31 = 7;
break;
case ("eight"):
Value31 = 8;
break;
case ("nine"):
Value31 = 9;
break;
case ("ten"):
Value31 = 10;
break;
case ("Jack"):
Value31 = 10;
break;
case ("Queen"):
Value31 = 10;
break;
case ("King"):
Value31 = 10;
break;
case ("Ace"):
Value31 = 11;
break;
default:
throw new System.ArgumentOutOfRangeException("name", "name should have one of the following values: two, three, four, five, six, seven, eight, nine, ten, Jack, Queen, King, Ace");
}
}
}
}
答案 0 :(得分:1)
您可以直接在enum
声明中指定值,如下所示:
public enum RankPossibleValues {
two =2,
three=3,
four=4,
five=5,
six=6,
seven=7,
eight=8,
nine=9,
ten=10,
Jack=11,
Queen=12,
King=13,
Ace=14
};
然后您可以通过简单的int
强制获取基础整数值,如下例所示:
int _value31 = (int)RankPossibleValues.two;
希望这会有所帮助。