定义:可设置或检索的字典键/值对。
命名空间: System.Collections
程序集: mscorlib(在 mscorlib.dll 中)
C# 语言中的 foreach 语句(在 Visual C++ 中为 for each,在 Visual Basic 中为 For Each)需要集合中每个元素的类型。由于 IDictionary 的每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型。而是 DictionaryEntry 类型。
/*foreach 语句是对枚举数的包装,它只允许从集合中读取,不允许写入集合。*/
下面的示例演示如何使用 DictionaryEntry 来循环访问 Hashtable 对象。
1 // A simple example for the DictionaryEntry structure. 2 using System; 3 using System.Collections; 4 5 class Example 6 { 7 public static void Main() 8 { 9 // Create a new hash table. 10 // 11 Hashtable openWith = new Hashtable(); 12 13 // Add some elements to the hash table. There are no 14 // duplicate keys, but some of the values are duplicates. 15 openWith.Add("txt", "notepad.exe"); 16 openWith.Add("bmp", "paint.exe"); 17 openWith.Add("dib", "paint.exe"); 18 openWith.Add("rtf", "wordpad.exe"); 19 20 // When you use foreach to enumerate hash table elements, 21 // the elements are retrieved as KeyValuePair objects. 22 Console.WriteLine(); 23 foreach (DictionaryEntry de in openWith) 24 { 25 Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); 26 } 27 } 28 } 29 30 /* This code example produces output similar to the following: 31 32 Key = rtf, Value = wordpad.exe 33 Key = txt, Value = notepad.exe 34 Key = dib, Value = paint.exe 35 Key = bmp, Value = paint.exe 36 */
表示键/值对的集合,这些键/值对根据键的哈希代码进行组织。
每个元素是一个存储在 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担当索引的功能
支持版本
.NET Framework
受以下版本支持:3.5、3.0、2.0、1.1、1.0
.NET Compact Framework
受以下版本支持:3.5、2.0、1.0
XNA Framework
受以下版本支持:2.0、1.0