什么是 C# 中的 Hashtable 类?
Hashtable类表示基于键的哈希码组织的键值对的集合。它使用键来访问集合中的元素。
Hashtable类中的一些常用方法是-
将具有指定键和值的元素添加到Hashtable中。
从哈希表中删除所有元素。
确定Hashtable是否包含特定键。
确定Hashtable是否包含特定值。
下面是一个示例,展示了C#中Hashtable类的用法。
示例
using System;
using System.Collections;
namespace Demo {
class Program {
static void Main(string[] args) {
Hashtable ht = new Hashtable();
ht.Add("D01", "Finance");
ht.Add("D02", "HR");
ht.Add("D03", "Operations");
if (ht.ContainsValue("Marketing")) {
Console.WriteLine("This department name is already in the list");
} else {
ht.Add("D04", "Marketing");
}
ICollection key = ht.Keys;
foreach (string k in key) {
Console.WriteLine(k + ": " + ht[k]);
}
Console.ReadKey();
}
}
}上面我们已经使用Hashtable类add()方法添加具有键值对的元素。
Hashtable ht = new Hashtable();
ht.Add("D01", "Finance");
ht.Add("D02", "HR");
ht.Add("DO3", "Operations");输出结果D04: Marketing D02: HR D03: Operations D01: Finance