在這種情況下使用一個枚舉試圖適合一個圓形孔中的方形釘。儘管XML對於你想要做的事情來說過於誇張。
請改用字典。這樣,就有了一個直接的'key => value'關係,這個值可以是任何東西。
爲1-1串串關係使用:
Dictionary<string, string> dictA = new Dictionary<string, string>();
dictA.Add("string1", "value1");
dictA.Add("string2", "value2");
dictA.Add("string3", "value3");
訪問所有的字典使用的值是:
foreach (KeyValuePair<string, string> item in dictA)
{
Console.WriteLine("Key: {0}; Value: {1};", item.Key, item.Value);
}
如果你需要一個1 2 1-3或1-n字符串關係使用此:
Dictionary<string, List<string>> dictB = new Dictionary<string, List<string>>();
dictB.Add("string1", new List<string>() {"value1A", "value1B"});
dictB.Add("string2", new List<string>() {"value2A", "value2B"});
dictB.Add("string3", new List<string>() {"value3A", "value3B"});
訪問所有的字典的值的使用:
foreach (KeyValuePair<string, List<string>> item in dictB)
{
Console.WriteLine("Key: {0}; Values: {1}, {2};", item.Key, item.Value[0], item.Value[1]);
}
如果你需要一個交錯排列的關係,使用這樣的:
Dictionary<string, List<string>> dictB = new Dictionary<string, List<string>>();
dictB.Add("string1", new List<string>() {"value1A", "value1B, value1C"});
dictB.Add("string2", new List<string>() {"value2A", "value2B, value2C, value2D"});
dictB.Add("string3", new List<string>() {"value3A", "value3B"});
訪問所有的字典使用的值這個:
foreach (KeyValuePair<string, List<string>> item in dictB)
{
string values = "";
int valLen = ((List<string>)item.Value).Count;
for (int i = 0; i < valLen; i++)
{
if (i == (valLen - 1))
{
values += item.Value[i] + "";
}
else
{
values += item.Value[i] + ", ";
}
}
Console.WriteLine("Key: {0}; Values: {1};", item.Key, values);
}
要得到一個特定的鍵的值是這樣的:
string match = "string2";
if (dictD.ContainsKey(match))
{
Console.WriteLine("The value for Key='{0}' is: '{1}'", match, dictD[match]);
}
一個枚舉就是一個榮耀的詞典。這就是爲什麼你不會在很多其他語言(尤其是動態類型語言)中看到它們的原因。
雖然不理想我決定這可能是最簡單的解決方案。 – haymansfield 2010-06-23 08:18:56