Better use HashTable or switch case(更好地使用 HashTable 或 switch case)
问题描述
我不确定哪个更好.我需要解析输入字符串的每个字符并获取该字符的替换字符串.对于某些对象,所有字母数字字符都是允许的,因此使用 switch/case 会导致大量代码并降低可读性和可维护性,但我可以使用静态方法.使用HashTable也需要很多代码
I'm not sure which one is better. I need to parse each character of an input string and get a replacing string for the character. For some objects all alphanumeric characters are allowed so using switch/case will cause a lot of code and reduce readability and maintainability but I can use a static method. Using a HashTable also requires a lot of code
使用静态方法:
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;
}
在性能和内存分配方面有哪些优势/劣势?
What are the advantages/disadvantages concerning performance and memory allocation?
推荐答案
我会使用 HashTable,因为代码更具可读性和可维护性:有一天你可以决定加载替代字符串来自 XML 文件,这样您就不会更改代码来更改映射.
I'd use the HashTable, because the code is more readable and maintainable: you could one day decide to load the subtitution strings from an XML file, so that you won't change the code to change the mappings.
这篇关于更好地使用 HashTable 或 switch case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更好地使用 HashTable 或 switch case
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
