using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace ConsoleTest
{
public class hashtable
{
static Hashtable ht = new Hashtable(); //创建一个Hashtable实例
public void Ht()
{
ht.Add("E", "e");//添加keyvalue键值对
ht.Add("A", "a");
ht.Add("C", "c");
ht.Add("B", "b");
string s = (string)ht["A"];
if (ht.Contains("E")) //判断哈希表是否包含特定键,其返回值为true或false
Console.WriteLine("the E key exist");
ht.Remove("C");//移除一个keyvalue键值对
Console.WriteLine(ht["A"]);//此处输出a
Console.WriteLine(ht["A"]); //此处将不会有任何输出
ArrayList akeys = new ArrayList(ht.Keys); //别忘了导入System.Collections
akeys.Sort(); //按字母顺序进行排序
foreach(string skey in akeys)
{
Console.Write(skey + ":");
Console.WriteLine(ht[skey]); //排序后输出
}
ht.Clear();//移除所有元素
}
}
}
测试:
#region hashtable的使用
hashtable httable = new hashtable();
httable.Ht();
#endregion
输出: