2011-04-27 70 views

回答

23

如果您知道要存储的特定类型,则可以使用Hashtable类或Dictionary<TKey, TValue>

例子:

// Loose-Type 
Hashtable hashTable = new Hashtable(); 
hashTable.Add("key", "value"); 
hashTable.Add("int value", 2); 
// ... 
foreach (DictionaryEntry dictionaryEntry in hashTable) { 
    Console.WriteLine("{0} -> {1}", dictionaryEntry.Key, dictionaryEntry.Value); 
} 

// Strong-Type 
Dictionary<string, int> intMap = new Dictionary<string, int>(); 
intMap.Add("One", 1); 
intMap.Add("Two", 2); 
// .. 
foreach (KeyValuePair<string, int> keyValue in intMap) { 
    Console.WriteLine("{0} -> {1}", keyValue.Key, keyValue.Value); 
} 
+0

非常感谢你。但是如何获得粒子的值。例如,我想在这里得到两个值... – Saravanan 2011-04-27 10:10:21

+1

你可以像普通的数组访问器那样使用intMap [“Two”]。由于强类型,你将得到一个“int”类型的对象,而使用Hashtable你只能得到一个“对象”。 – 2011-04-27 10:11:23

+0

你可以用这种方式得到一个值:intvalue = hashTable [“Two”] – Kevin 2011-04-27 10:13:23

2

您可以查看Dictionary数据结构,采用string的密钥类型,无论您的数据的类型是值类型(可能object如果多个类型的数据项)。