using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace HashtableExample
{
class Program
{
static void 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";
openWith["rtf"] = "测试1";
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("8888888888888Value added for key = \"ht\": {0}", openWith["ht"]);
}
// foreach枚举hash表的元素
Console.WriteLine();
foreach (DictionaryEntry de in openWith)
{
Console.WriteLine("555555555Key = {0}, Value = {1}", de.Key, de.Value);
}
// Values属性获取
ICollection valueColl = openWith.Values;
// ValueCollection的值输出
Console.WriteLine();
foreach (string s in valueColl)
{
Console.WriteLine("66666666Value = {0}", s);
}
ICollection keyColl = openWith.Keys;
// ValueCollection的值输出
Console.WriteLine();
foreach (string s in keyColl)
{
Console.WriteLine("2222222222222Key = {0}", s);
}
// Remove方法删除key/value.
Console.WriteLine("\nRemove(\"doc\")");
Console.WriteLine("删除前 "+openWith["doc"]);
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
Console.Read();
}
}
}
评论