我想知道如何在 C# 4.0 中存储键/值对?
例如,在 Java 中,HashTable
或 HashMap
用于存储键/值对。但是我如何在 C# 中实现呢?
最佳答案
您可以使用 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);
}
关于c# - 如何在 C#(4.0) 中存储键/值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5802291/