我写了一个返回的方法
List<KeyValuePair<CommandType, List<string>>>
Run Code Online (Sandbox Code Playgroud)
CommandType
属于Type enum
public enum CommandType
{
Programmed,
Manual
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,KeyValuePair
有时候的值是一个enum
,有时它是一个字符串列表,但我需要将所有内容保存KeyValuePair
在一个列表中.
目前,我将值作为keyvaluepair中的对象传递,当方法返回列表并通过它迭代时,基于键,我将值转换回其原始类型.
有没有更好的方法来实现这个?
这是一个示例代码
public enum ProgrammedCommands
{
Sntp,
Snmp,
}
private List<KeyValuePair<CommandType, object>> GetCommandsFromTemplate(string[] templateLines)
{
var list = new List<KeyValuePair<CommandType, object>>();
if (templateLines != null)
for (int lineIndex = 0; lineIndex < templateLines.Length; lineIndex++)
{
if (templateLines[lineIndex].Contains("!*") && templateLines[lineIndex].Contains("*!"))
{
KeyValuePair<CommandType, object> ProgrammedSetting;
List<string> programmedCommandList;
if (templateLines[lineIndex].Contains("SNTP - SNTP Server Commands"))
{
ProgrammedSetting = new KeyValuePair<CommandType, object>(CommandType.Programmed, ProgrammedCommands.Sntp);
list.Add(ProgrammedSetting);
}
else if (templateLines[lineIndex].Contains("MANUAL"))
{
lineIndex++;
List<string> manual = new List<string>();
while (true)
{
if (lineIndex >= templateLines.Length)
break;
if (templateLines[lineIndex].Contains("!!["))
lineIndex++;
else if (templateLines[lineIndex].Contains("]!!"))
break;
else
{
manual.Add(templateLines[lineIndex]);
lineIndex++;
}
}
ProgrammedSetting = new KeyValuePair<CommandType, object>(CommandType.Manual, manual);
list.Add(ProgrammedSetting);
}
}
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
如果您想对不同类型使用单个存储,由于值的类型只能在运行时确定,那么您应该使用object
type 来装箱值,然后当您需要以类型化方式处理值时,请检查找到它的类型并将其拆箱为所需的类型并使用它。
因此,您可以根据您的要求使用以下数据结构之一:
\n\nDictionary<CommandType, object>
\xe2\x86\x90 密钥应该是唯一的。List<KeyValuePair<CommandType, object>>
\xe2\x86\x90 对的密钥不需要是唯一的。注意:您可能可以想象解决方案,例如创建一个公共基类BaseType
并从和 派生两个不同的ListContainer
和在运行时创建和并将其存储在EnumContainer
BaseType
ListContainer
EnumContainer
Dictionary<CommandType, BaseType>
. 这样的结构可能只是可以帮助您将存储限制为所需的类型,而不是使用对象。
归档时间: |
|
查看次数: |
334 次 |
最近记录: |