c# - 如何在 C#(4.0) 中存储键/值对?

标签 c# c#-4.0

我想知道如何在 C# 4.0 中存储键/值对?

例如,在 Java 中,HashTableHashMap 用于存储键/值对。但是我如何在 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/

相关文章:

asp.net-mvc-3 - 如何为电子邮件地址创建“不得匹配”属性

c# - Linq使用案例

c# - 在沙盒模式下执行任意 C# 代码?

c# - 元组类中的命名比 "Item1"、 "Item2"更好

c# - Visual Studio 说 "Method must have a return type"

c# - Azure表存储跨多个分区批量插入?

c# - .NET 桌面应用程序架构 - 客户端服务器 C#、SQL

c# - 以编程方式隐藏 WPF 功能区标题

c# - 使用 C# 自动设置 Internet Explorer/Windows 以使用 Socks5 代理

wpf - 应用程序级别未处理的异常未创建新文件