草随原

骏马

导航

数组集合篇-Hashtable类的使用

Hashtable类:

一基本概念:
    1:数组和ArrayList类型都提供了一种方式将一个整数索引映射到一个元素。

    注意:这里只提到了数组和ArrayList有这样的功能。


    2:Hashtable里具有的新的功能,作为映射的来源不是int类型,而是其他类型。如:string ,double,Time等等。这个实际上就是关联数组。

   
    3:在Hashtable中插入一对key/value时,它将自动跟踪哪个key从属于哪个value。并允许你获取与一个指定的key关联的value。

   
    4:Hashtable中不能包含重复的key,可以使用ContainsKey方法来测试一个Hashtable中是否已经包含一个特定的key。

   
    5:使用foreach语句来遍历一个Hashtable时,会返回一个DictionaryEntry。DictionaryEntry类允许你通过Key属性和Value属性来访问两个数组中的key和value元素。DictionaryEntry:字典条目入口。)

例程:

using System;
using System.Collections;
....
Hashtable ages = new Hashtable();
...

//填充Hashtable
ages["John"] = 41;
ages["Diana"] = 42;
ages["James"] = 13;
ages["Francesca"] = 11;
...

//使用一个foreach语句来遍历;
//迭代器生成一个DictionaryEntry对象,其中包含一个键/值对。
foreach(DictionaryEntry element in ages)
{

 string name = (string)element.Key;
 int age = (int)element.Value;  //这里我注意到这里实际上也是一次拆箱工作。
 Console.WriteLine("Name:{0},Age:{1}",name,age);

}

程序运行输出:
Name:James,Age:13
Name:John,Age:41
Name:Francesca,Age:11
Name:Diana,Age:42

posted on 2007-03-27 09:04  淄衣  阅读(306)  评论(1)    收藏  举报