Evl*_*tnt 5 c# architecture enums
我使用类卡,其中包含2个枚举属性(套件 - 心形钻石黑桃和俱乐部)和卡值从2到A.并覆盖ToString()方法返回类似Ah Ad等的东西.一切都好,但枚举值无法启动有了数字,因此枚举的卡片值看起来像x2,x3,x4 ......它不漂亮.
还需要简单的方法来解析单个字符串中的几张卡片.
谁知道设计这门课程的最佳方法?
你不能将 Jack、Queen、King 和 Ace 分别指定为 11、12、13 和 14 吗?它最终看起来像这样:
public class Card
{
public int Value { get; private set; }
public enum SuitType
{
Clubs, Spades, Hearts, Diamonds
}
public SuitType Suit { get; private set; }
public Card(int value, SuitType suit)
{
Suit = suit;
Value = value;
}
public Card(string input)
{
if (input == null || input.Length < 2 || input.Length > 2)
throw new ArgumentException();
switch (input[0])
{
case 'C': case 'c':
Suit = SuitType.Clubs;
break;
case 'S': case 's':
Suit = SuitType.Spades;
break;
case 'H': case 'h':
Suit = SuitType.Hearts;
break;
case 'D': case 'd':
Suit = SuitType.Diamonds;
break;
default:
throw new ArgumentException();
}
int uncheckedValue = (int)input[1];
if (uncheckedValue > 14 || uncheckedValue < 1)
throw new ArgumentException();
Value = uncheckedValue;
}
public string encode()
{
string encodedCard = "";
switch (Suit)
{
case SuitType.Clubs:
encodedCard += 'c';
break;
case SuitType.Spades:
encodedCard += 's';
break;
case SuitType.Hearts:
encodedCard += 'h';
break;
case SuitType.Diamonds:
encodedCard += 'd';
break;
}
encodedCard += (char) Value;
return encodedCard;
}
public override string ToString()
{
string output = "";
if (Value > 10)
{
switch (Value)
{
case 11:
output += "Jack";
break;
case 12:
output += "Queen";
break;
case 13:
output += "King";
break;
case 14:
output += "Ace";
break;
}
}
else
{
output += Value;
}
output += " of " + System.Enum.GetName(typeof(SuitType), Suit);
return output;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我添加了一些字符串功能。Card(string input)我从乔·汉纳的回答中获取了结构。