常见功能 在哈希表中添加一个key/键值对:HashtableObject.Add(key,); 在哈希表中去除某个key/键值对:HashtableObject.Remove(key); 从哈希表中移除所有元素: HashtableObject.Clear(); 判断哈希表是否包含特定键key: HashtableObject.Contains(key); 下面控制台程序将包含以上所有操作: using System; using System.Collections; //使用Hashtable时,必须引入这个命名空间 class hashtable { public static void Main() { Hashtable ht=new Hashtable(); //创建一个Hashtable实例 //key值唯一,value值可以重复. ht.Add("E","e");//添加key/键值对 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");//移除一个key/键值对 Console.WriteLine(ht["A"]);//此处输出a ht.Clear();//移除所有元素 Console.WriteLine(ht["A"]); //此处将不会有任何输出 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Collections;namespace ConsoleApplication97 { class Program { static void Main(string[] args) { Dictionary<string, string> a = new Dictionary<string, string>(); Hashtable c = new Hashtable(); for (int i = 0; i < 1000000; i++) { a.Add(i.ToString(), (i + 1).ToString()); c.Add(i.ToString(), (i + 1).ToString()); } Stopwatch watch = new Stopwatch(); watch.Start(); Console.WriteLine(a["999999"]); Console.WriteLine(watch.ElapsedTicks); watch.Reset(); watch.Start(); Console.WriteLine(c["999999"]); Console.WriteLine(watch.ElapsedTicks); Console.ReadKey(); } } } hashtable取值确实比dictionary要快
读取xml配置文件等
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Collections;namespace ConsoleApplication97
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> a = new Dictionary<string, string>();
Hashtable c = new Hashtable();
for (int i = 0; i < 1000000; i++)
{
a.Add(i.ToString(), (i + 1).ToString());
c.Add(i.ToString(), (i + 1).ToString());
}
Stopwatch watch = new Stopwatch();
watch.Start();
Console.WriteLine(a["999999"]);
Console.WriteLine(watch.ElapsedTicks);
watch.Reset();
watch.Start();
Console.WriteLine(c["999999"]);
Console.WriteLine(watch.ElapsedTicks);
Console.ReadKey();
}
}
}
hashtable取值确实比dictionary要快