C# 读取时更有效地转换数组中的值
我正试图找到一种更有效的方法,从sruct数组中读取值,并将其转换为更有意义的内容,如数组中存储了“C”,我希望它以“Clubs”的形式返回,以下是我目前为止的方法,效率非常低C# 读取时更有效地转换数组中的值,c#,arrays,struct,C#,Arrays,Struct,我正试图找到一种更有效的方法,从sruct数组中读取值,并将其转换为更有意义的内容,如数组中存储了“C”,我希望它以“Clubs”的形式返回,以下是我目前为止的方法,效率非常低 public static void DisplayHandData(Card[] data) { Console.WriteLine(); //test values loaded into array in correct positions Consol
public static void DisplayHandData(Card[] data)
{
Console.WriteLine();
//test values loaded into array in correct positions
Console.WriteLine("** Values in array **");
//read values out to check against if statements
for (int records = 0; records < data.Length; records++)
{
Console.WriteLine(data[records].suit);
Console.WriteLine(data[records].value);
}
DrawBlankLine();
DrawLine();
DrawBlankLine();
Console.WriteLine("** Values in suit **");
if (data[0].suit == 'C')
{
string suit = "Clubs";
Console.WriteLine("Card 1: {0} of {1}", data[0].value, suit);
}
else if (data[0].suit == 'D')
{
string suit = "Diamonds";
Console.WriteLine("Card 1: {0} of {1}", data[0].value, suit);
}
else if (data[0].suit == 'H')
{
string suit = "Hearts";
Console.WriteLine("Card 1: {0} of {1}", data[0].value, suit);
}
else if (data[0].suit == 'S')
{
string suit = "Spades";
Console.WriteLine("Card 1: {0} of {1}", data[0].value, suit);
}
else
publicstaticvoiddisplayHandData(卡片[]数据)
{
Console.WriteLine();
//将测试值加载到数组中的正确位置
Console.WriteLine(“**数组中的值**”);
//读取值以对照if语句进行检查
for(int记录=0;记录
我还需要对数据[0]执行相同的操作。值作为ACE存储为值14、13等
任何帮助都将不胜感激。您可以使用字典:
private static Dictionary<char, string> suitDictionary = new Dictionary<char, string>
{
{ 'C', "Clubs" },
{ 'H', "Hearts" },
// ...
}
对于.value下的struct中的Ace、King等值,这将如何工作?您没有显示
Card
类,因此我不知道value
的类型,但您可以创建一个单独的字典来保存卡值。struct是“public struct Card”{public char suit;//'C'-Clubs,'D'-Diamonds,'H'-Hearts//和'S'-Spades public int value;///2-14–2-10,杰克,王后,国王,王牌}`我遗漏了一些东西,因为我现在有一个错误:在尝试访问SuiteName时需要对象引用。是的,当您从静态方法调用字典时,需要将字典声明为static
。
string suitName = suitDictionary[data[0].suit];