【发布时间】:2012-02-14 13:09:20
【问题描述】:
我不确定哪个更好。我需要解析输入字符串的每个字符并获取该字符的替换字符串。对于某些对象,所有字母数字字符都是允许的,因此使用 switch/case 会导致大量代码并降低可读性和可维护性,但我可以使用静态方法。使用HashTable也需要很多代码
使用静态方法:
private static string EncodeChar(char c)
{
var symbols = string.Empty;
switch (c)
{
case '0':
symbols = "Test";
break;
case '1':
symbols = "Hello";
break;
[...]
}
symbols;
}
使用哈希表:
private static Hashtable table = CreateTable();
private static Hashtable CreateTable()
{
var table = new HashTable();
table.Add('0',"Test");
table.Add('1', "Hello");
[...]
return table;
}
private static string EncodeChar(char c)
{
return table.ContainsKey(c) ? table[c].ToString() : string.Empty;
}
编码方法:
public void Encode()
{
string output = string.Empty;
for (int i = 1; i < Data.Length; i++)
{
output = string.Concat(output, EncodeChar(Data[i]));
}
EncodedData = output;
}
在性能和内存分配方面有哪些优点/缺点?
【问题讨论】:
-
是不是必须在这些方法之间进行选择?或者您可以尝试其他方法吗?
-
也可以尝试其他方法 :-)
-
使用
Dictionary<char, string>而不是HashTable——它的效率要高得多,而且更不容易出现意外的类型错误。 -
你说得对,字典更好:-)
标签: c# hashtable switch-statement