zoukankan      html  css  js  c++  java
  • 键值对Dictionary、KeyValuePair、Hashtable 简单使用。

    KeyValuePair是单个的键值对对象。KeyValuePair可用于接收combox选定的值。

    例如:KeyValuePair<string, object> par = (KeyValuePair<string, object>)shoplistcomboBox.SelectedItem;

    单线程程序中推荐使用 Dictionary, 有泛型优势, 且读取速度较快, 容量利用更充分。

    Hashtable是一个集合。在多线程程序中推荐使用 Hashtable, 默认的 Hashtable 允许单线程写入, 多线程读取, 对 Hashtable 进一步调用 Synchronized() 方法可以获得完全线程安全的类型. 而 Dictionary 非线程安全, 必须人为使用 lock 语句进行保护, 效率大减。

    1.键值对Dictionary:Dictionary<string,string>键值对的使用

    public void CreateDictionary()
    {
        Dictionary<string,string> dic=new Dictionary<string,string>();
        //添加
        dic.Add("1","one");
        dic.Add("2","two");
        //取值
        string getone=dic["1"];
    }

    2.键值对KeyValuePair:KeyValuePair<string,string>

    因为KeyValuePair是单个的键值对对象,可以用来遍历Dictionary字典,或保存combox选择的值。

    public void usekeyvaluepair()
    {
        foreach (KeyValuePair<string, string> item in dic)
        {
            string a = item.Key;
            string b = item.Value;
        }
    }

    3.哈希集合Hashtable

    Hashtable是非泛型集合,所以在检索和存储值类型时通常会发生装箱与拆箱的操作。 

    public void CreateHashtable()
    {
        Hashtable hs = new Hashtable();
        hs.Add(1,"one");
        hs.Add("2","two");
        string a=hs[1].ToString();
        string b = hs["2"].ToString();
    }

     Hashtable集合补充:遍历集合,可使用DictionaryEntry类(定义可设置或检索的键值对)

    Hashtable hs = new Hashtable();
    hs.Add(1, "one");
    hs.Add("2", "two");
     foreach (DictionaryEntry item in hs)
    {
          string a = item.Key.ToString();
          string b = item.Value.ToString();
    }

    使用foreach遍历是不能修改值的,只能读取值,迭代变量相当于一个局部只读变量。可使用for循环修改。

  • 相关阅读:
    软工1816 · 第四次作业
    Alpha 冲刺 (3/10)
    Alpha 冲刺 (2/10)
    Alpha 冲刺 (1/10)
    软工 第七次作业
    软工实践第八次作业
    软工实践第六次作业——团队选题报告
    软工实践第二次结对作业(作业五)
    软工第四次作业
    软工实践第三次作业
  • 原文地址:https://www.cnblogs.com/yxys/p/5205891.html
Copyright © 2011-2022 走看看