using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace HashtableExample ...{ class Program ...{ staticvoid Main(string[] args) ...{ //创建一个新的hash表. Hashtable openWith =new Hashtable(); //添加一些元素 openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); //如果新添加的元素已经在表中,则抛出异常 try ...{ openWith.Add("txt", "winword.exe"); } catch ...{ Console.WriteLine("带有Key是 "txt" 的元素已经存在."); } Console.WriteLine("For key = "rtf", value = {0}.", openWith["rtf"]); openWith["rtf"] ="winword.exe"; Console.WriteLine("For key = "rtf", value = {0}.", openWith["rtf"]); openWith["doc"] ="winword.exe"; //如果寻找的不在表中,则抛出异常 try ...{ Console.WriteLine("For key = "tif", value = {0}.", openWith["tif"]); } catch ...{ Console.WriteLine("Key = "tif" is not found."); } // 在插入之前,ContainsKey用来测试keys if (!openWith.ContainsKey("ht")) ...{ openWith.Add("ht", "hypertrm.exe"); Console.WriteLine("Value added for key = "ht": {0}", openWith["ht"]); } // foreach枚举hash表的元素 Console.WriteLine(); foreach (DictionaryEntry de in openWith) ...{ Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); } // Values属性获取 ICollection valueColl = openWith.Values; // ValueCollection的值输出 Console.WriteLine(); foreach (string s in valueColl) ...{ Console.WriteLine("Value = {0}", s); } ICollection keyColl = openWith.Keys; // ValueCollection的值输出 Console.WriteLine(); foreach (string s in keyColl) ...{ Console.WriteLine("Key = {0}", s); } // Remove方法删除key/value. Console.WriteLine(" Remove("doc")"); openWith.Remove("doc"); if (!openWith.ContainsKey("doc")) ...{ Console.WriteLine("Key "doc" is not found."); } } } }
带有Key是 "txt" 的元素已经存在. For key = "rtf", value = wordpad.exe. For key = "rtf", value = winword.exe. For key = "tif", value = . Value added for key = "ht": hypertrm.exe
Key = doc, Value = winword.exe Key = rtf, Value = winword.exe Key = txt, Value = notepad.exe Key = ht, Value = hypertrm.exe Key = dib, Value = paint.exe Key = bmp, Value = paint.exe
Value = winword.exe Value = winword.exe Value = notepad.exe Value = hypertrm.exe Value = paint.exe Value = paint.exe
using System;using System.Collections.Generic;using System.Text;using System.Collections;namespace HashtableExample...{ class Program ...{ static void Main(string[] args) ...{