转载 hashtable和dictionary的区别

1:单线程程序中推荐使用 Dictionary, 有泛型优势, 且读取速度较快, 容量利用更充分.
2:多线程程序中推荐使用 Hashtable, 默认的 Hashtable 允许单线程写入, 多线程读取, 对 Hashtable 进一步调用 Synchronized() 方法可以获得完全线程安全的类型. 而 Dictionary 非线程安全, 必须人为使用 lock 语句进行保护, 效率大减.
 3:Dictionary 有按插入顺序排列数据的特性 (注: 但当调用 Remove() 删除过节点后顺序被打乱), 因此在需要体现顺序的情境中使用 Dictionary 能获得一定方便.

 

Hashtable 类和 Dictionary<(Of <(TKey, TValue>)>) 泛型类实现 IDictionary 接口

Dictionary<(Of <(TKey, TValue>)>) 泛型类还实现 IDictionary<(Of <(TKey, TValue>)>) 泛型接口。因此,这些集合中的每个元素都是一个键/值对。

Dictionary<(Of <(TKey, TValue>)>) 类与 Hashtable 类的功能相同
对于值类型,特定类型(不包括 Object)的 Dictionary<(Of <(TKey, TValue>)>) 的性能优于 Hashtable,这是因为 Hashtable 的元素属于 Object 类型,所以在存储或检索值类型时通常发生装箱和取消装箱操作。

HashTable ht=new HashTable();//实现 IDictionary接口
ht.Add(1,"A");
ht.Add(2,"B");
ht.Add(3,"c");
foreach(DictionaryEntry de in ht)//HashTable返回的是DictionaryEntry类型
 {
    de.Key;
    de.Value;
 }

Dictionary<int,string> myDictionary=new Dictionary<int,string>();//实现IDictionary接口,IDictionary<T key,T value>类
myDictionary.Add(1,"a");
myDictionary.Add(2,"b");
myDictionary.Add(3,"c");
foreach(int i in myDictionary.Keys)
{
  Console.WriteLine("Key="+i+"Value="+myDictionary);
}
Or
foreach(KeyValuePair<string, double> temp in myDictionary)//返回的是KeyValuePair<string, double>泛型数组
  {
       temp.Key;
       temp.Value;
  }

 //使用索引器来取值时,如果键不存在就会引发异常
    try
    {
        Console.WriteLine("不存在的键""fff""的键值为:" + myDic["fff"]);
    }
    catch (KeyNotFoundException ex)
    {
        Console.WriteLine("没有找到键引发异常:" + ex.Message);
    }
    //解决上面的异常的方法是使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值
    string value = "";
    if (myDictionary.TryGetValue("fff", out value))
    {
        Console.WriteLine("不存在的键""fff""的键值为:" + value );
    }
    else
    {     
        Console.WriteLine("没有找到对应键的键值"); 
    }
    
    //下面用foreach 来遍历键值对
    //泛型结构体 用来存储健值对
    foreach (KeyValuePair<string, string> temp in myDictionary)
    {
        Console.WriteLine( temp .Key, temp .Value);
    }
    //获取值得集合
    foreach (string s in myDictionary.Values)
    {
        Console.WriteLine("value"+ s);
    }
    //获取值得另一种方式
    Dictionary<string, string>.ValueCollection values = myDictionary.Values;
    foreach (string s in values)
    {
        Console.WriteLine("value:"+ s);
    }

 

posted @ 2013-12-17 18:16  chopic  阅读(117)  评论(0编辑  收藏  举报