Hashtable
类表示基于键的哈希码组织的键和值对的集合。它使用键来访问集合中的元素。
当需要使用键访问元素时,可使用哈希表来标识有用的键值。哈希表中的每个项目都有一个键/值对。键用于访问集合中的项目。
Hashtable类的方法和属性
下表列出了Hashtable
类的一些常用属性:
属性 | 说明 |
---|---|
Count | 获取Hashtable 中包含的键值对的数量。 |
IsFixedSize | 获取一个值,指示Hashtable 是否具有固定大小。 |
IsReadOnly | 获取一个值,指示Hashtable 是否为只读。 |
Item | 获取或设置与指定键相关联的值。 |
Keys | 获取Hashtable 中包含ICollection 的键。 |
Values | 获取Hashtable 中一个包含的ICollection 的值。 |
下表列出了Hashtable
类的一些常用方法:
序号 | 方法 | 描述 |
---|---|---|
1 | public virtual void Add(object key, object value); |
将具有指定键和值的元素添加到Hashtable 中。 |
2 | public virtual void Clear(); |
从Hashtable 中删除所有元素。 |
3 | public virtual bool ContainsKey(object key); |
确定Hashtable 是否包含指定的键。 |
4 | public virtual bool ContainsValue(object value); |
确定Hashtable 是否包含指定值。 |
5 | public virtual void Remove(object key); |
从Hashtable 中删除指定键的元素。 |
例子
以下示例演示了上面所述的概念:
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("001", "Maxsu");
ht.Add("002", "Andy");
ht.Add("003", "Jame");
ht.Add("004", "Mausambe");
ht.Add("005", "Mr. Amlan");
ht.Add("006", "Mr. Arif");
ht.Add("007", "Ritesh");
ht.Add("008", "Sukida");
if (ht.ContainsValue("Nuha Ali"))
{
Console.WriteLine("This student name is already in the list");
}
else
{
ht.Add("018", "zaixian");
}
// Get a collection of the keys.
ICollection key = ht.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + ht[k]);
}
Console.ReadKey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
006: Mr. Arif
007: Ritesh
008: Sukida
018: zaixian
003: Jame
002: Andy
004: Mausambe
001: Maxsu
005: Mr. Amlan