C# 是否有任何好的替代结构用于内部开关盒?
我有一个在程序中显示文本的开关盒。我想知道,我可以使用字典或枚举的数字和文字?或者像这样使用开关盒好吗C# 是否有任何好的替代结构用于内部开关盒?,c#,C#,我有一个在程序中显示文本的开关盒。我想知道,我可以使用字典或枚举的数字和文字?或者像这样使用开关盒好吗 string result; int number = int.Parse(Console.Readline()); switch (number) { case 1: result += "ten"; break; case 2: result += "twenty"; break; case 3:
string result;
int number = int.Parse(Console.Readline());
switch (number)
{
case 1:
result += "ten";
break;
case 2:
result += "twenty";
break;
case 3:
result += "thirty";
break;
case 4:
result += "fourty";
break;
case 5:
result += "fifty";
break;
case 6:
result += "sixty";
break;
case 7:
result += "seventy";
break;
case 8:
result += "eighty";
break;
case 9:
result += "ninety";
break;
default:
result += "";
break;
}
在这种情况下,使用
字典{int,string}
可能不会太冗长:
var dictionary = new Dictionary<int, string>(9)
{
{1, "ten"},
{2, "twenty"},
{3, "thirty"},
{4, "fourty"},
{5, "fifty"},
{6, "sixty"},
{7, "seventy"},
{8, "eighty"},
{9, "ninety"},
};
此外,如果您打算做很多字符串连接,请考虑用“代替代码”来代替<代码>结果< /代码> .< 对于执行大量字符串操作的例程(例如在循环中多次修改字符串的应用程序),重复修改字符串可能会造成严重的性能损失。另一种方法是使用StringBuilder,它是一个可变字符串类
这听起来可能有点原始,但如果您知道字符串将以连续顺序排列,为什么不使用字符串数组呢
string[] array = new string[] { "ten",
"twenty",
"thirty",
...
};
...
result += array[number-1];
string[] array = new string[] { "ten",
"twenty",
"thirty",
...
};
...
result += array[number-1];