Hashtable的遍历(DictionaryEntry)

来源:互联网 发布:苹果电脑怎么删除软件 编辑:程序博客网 时间:2024/05/10 13:12
 

定义可设置或检索的字典键/值对。

命名空间:System.Collections
程序集:mscorlib(在 mscorlib.dll 中)

foreach 语句是对枚举数的包装,它只允许从集合中读取,不允许写入集合。

C# 语言中的 foreach 语句(在 Visual C++ 中为 for each,在 Visual Basic 中为 For Each)需要集合中每个元素的类型。由于 IDictionary 的每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型。而是 DictionaryEntry 类型。

下面的示例演示如何使用 DictionaryEntry 来循环访问 Hashtable 对象。

using System;using System.Collections;class Example{    public static void Main()    {        // Create a new hash table.        //        Hashtable openWith = new Hashtable();        // Add some elements to the hash table. There are no         // duplicate keys, but some of the values are duplicates.        openWith.Add("txt", "notepad.exe");        openWith.Add("bmp", "paint.exe");        openWith.Add("dib", "paint.exe");        openWith.Add("rtf", "wordpad.exe");        // When you use foreach to enumerate hash table elements,        // the elements are retrieved as KeyValuePair objects.        Console.WriteLine();        foreach (DictionaryEntry de in openWith)        {            Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);        }    }}


另一种方法:

System.Collections.IDictionaryEnumerator ht = ht.GetEnumerator();while (ht.MoveNext()){          ht.Key.ToString();//键     ht.Value.ToString();//值            //这里已经取到当前的键、值对了,怎么输出和存储就看自己的了    }


 

Hashtable 
     表示键/值对的集合,这些键/值对根据键的哈希代码进行组织。
     每个元素是一个存储在 DictionaryEntry 对象中的键/值对。键不能为空引用(Visual Basic 中为 Nothing),但值可以。

用作 Hashtable 中的键的对象必须实现或继承 Object.GetHashCode 和 Object.Equals 方法。如果键相等性只是引用相等性,这些方法的继承实现将满足需要。此外,如果该键存在于 Hashtable 中,那么当使用相同参数调用这些方法时,这些方法必须生成相同的结果。只要键对象用作 Hashtable 中的键,它们就必须是永远不变的。

当把某个元素添加到 Hashtable 时,将根据键的哈希代码将该元素放入存储桶中。该键的后续查找将使用键的哈希代码只在一个特定存储桶中搜索,这将大大减少为查找一个元素所需的键比较的次数。

Hashtable 的加载因子确定元素与存储桶的最大比率。加载因子越小,平均查找速度越快,但消耗的内存也增加。默认的加载因子 1.0 通常提供速度和大小之间的最佳平衡。当创建 Hashtable 时,也可以指定其他加载因子。

当向 Hashtable 添加元素时,Hashtable 的实际加载因子将增加。当实际加载因子达到此加载因子时,Hashtable 中存储桶的数目自动增加到大于当前 Hashtable 存储桶数两倍的最小质数。

Hashtable 中的每个键对象必须提供其自己的哈希函数,可通过调用 GetHash 访问该函数。但是,可将任何实现 IHashCodeProvider 的对象传递到 Hashtable 构造函数,而且该哈希函数用于该表中的所有对象。

总之:DictionaryEntry就是键值对
Key是键
Value是值
Hashtable 内的每一组对象就是一个DictionaryEntry 
例如我们要循环hashtable


foreach (DictionaryEntry de in myHashtable) {...}


Hashtable就是一个DictionaryEntry的集合
在一个Hashtable中
Key的值是不可以重复的,必须是唯一的,但Value的值可以是重复的
在查询时,Key担当索引的功能

 

http://apps.hi.baidu.com/share/detail/34942799

http://www.cnblogs.com/windteam/archive/2011/07/04/2097229.html

原创粉丝点击