static void Main(string[] args)
{
Hashtable openWith = new Hashtable();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp","paint.exe");
openWith.Add("dib","paint.exe");
openWith.Add("rtf","wordpad.exe");
Console.WriteLine("键= \"txt\",值 = {0}.",openWith["txt"]);
openWith["dib"] = "winword.exe"; //哈希表中的键不可修改,只能修改键对应的值
Console.WriteLine("键= \"dib\",值 = {0}.", openWith["dib"]);
openWith["doc"] = "winword.exe"; //如果对不存在的键设置值,将添加新的键值对(最好先判断某个键是否存在,再添加)
Console.WriteLine("键= \"doc\",值 = {0}.", openWith["doc"]);
//通常添加之前用ContainsKey来判断某个键是否存在
if(!openWith.ContainsKey("ht"))
{
openWith.Add("ht","hypertrm.exe");
Console.WriteLine("键= \"ht\",值 = {0}.", openWith["ht"]);
}
Console.WriteLine("哈希表遍历:");
foreach (DictionaryEntry de in openWith) //Hashtable 键值是DictionaryEntry类型
{
Console.WriteLine("键 = {0},值={1}",de.Key,de.Value);
}
Console.WriteLine("\n删除(\"doc\")");
openWith.Remove("doc"); //移除doc键值对
if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("键\"doc\"没有找到.");
}
//使用values属性操作哈希表中的值的集合
ICollection valueColl = openWith.Values; //得到哈希表值的集合
Console.WriteLine();
foreach (string s in valueColl) //对值的集合进行遍历
{
Console.WriteLine("值 = {0}",s); //输出哈希表中的值
}
//使用keys属性操作哈希表中的键的集合
ICollection keyColl = openWith.Keys; //得到哈希表键的集合
Console.WriteLine();
foreach (string s in keyColl) //对键的集合进行遍历
{
Console.WriteLine("键={0}", s); //输出哈希表中的值
}
Console.Read();
}
c#:hashtable用法
最新推荐文章于 2023-12-24 09:08:37 发布