2011-04-27 27 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如果多個類型的數據項)。