首页 > 编程知识 正文

键值对Dictionary、KeyValuePair、Hashtable 简单使用。

时间:2023-05-04 05:17:19 阅读:211891 作者:278

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循环修改。

转自博客园,博主:小丿悠悠

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。