Hashtable 和 Dictionary

hashtable

下面的示例说明如何对 Hashtable 创建、初始化并执行各种函数以及如何打印出其键和值

Code

System..::.Object
  System.Collections..::.Hashtable
    System.Configuration..::.SettingsAttributeDictionary
    System.Configuration..::.SettingsContext
    System.Data..::.PropertyCollection

    System.Printing.IndexedProperties..::.PrintPropertyDictionary

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class Hashtable : IDictionary, ICollection,
IEnumerable, ISerializable, IDeserializationCallback, ICloneable


Hashtable 和 Dictionary  

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

 2:单线程程序中推荐使用 Dictionary, 有泛型优势, 且读取速度较快, 容量利用更充分.
 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 类型,所以在存储或检索值类型时通常发生装箱和取消装箱操作。

Hashtableht=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;
  }

 

 

posted @ 2009-04-08 13:35  小贱  阅读(348)  评论(0编辑  收藏  举报