c#:hashtable用法

39 篇文章 2 订阅
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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值