2015-06-13 35 views
1

我有在我的程序中显示文本的开关盒。我不知道我可以使用字典或枚举数字和文本?还是这样使用开关盒好?有使用内部开关的情况下有什么好的替代结构?

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; 
} 

回答

2

这可能是一个有点不太冗长在那种情况下使用Dictionary{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"}, 
}; 

string dictionaryEntry; 
if (dictionary.TryGetValue(number, out dictionaryEntry)) 
{ 
    result += dictionaryEntry; 
} 

另外,如果你打算做了很多的字符串连接的,可以考虑使用StringBuilder而不是字符串result

对于执行大量字符串操作的例程(例如在循环中多次修改字符串的应用程序),重复修改字符串可能会导致严重的性能损失。另一种方法是使用StringBuilder,它是一个可变的字符串类。

+0

谢谢,我会用字典。 – Brkr

1

它可能听起来有点原始,但如果你知道字符串将按连续顺序,为什么不使用字符串数组?

string[] array = new string[] { "ten", 
           "twenty", 
           "thirty", 
           ... 
           }; 

... 

result += array[number-1]; 
相关问题