Hashtable和Dictionary的区别

概要:

System.Collections.Generic 中 Hashtable 和 Dictionary 的区别:

  • Hash表:当 Hashtable 不存在某个 key时,返回 null;
  • Dictionary:当 Dictionary 不存在某个 key时,抛出一个异常。

As some of you with the Whidbey preview bits have no doubt noticed, we introduced set of generic collection classes in System.Collections.Generic. Far from just making generic versions of the current collections, we took the time to revisit how we really expect people to use these types and, in some cases, learned from our mistakes in V1 of the framework.

One of the new collections is Dictionary<K, V>. The big change that we made from Hashtable has caused a fair amount of internal debate so I thought it would be interesting to see what actual, real-live, customers think of the issue. In brief, with Hashtable's indexer, if the key is not found null is returned, with Dictionary<K,V>'s indexer an exception is thrown.

For example:

Hashtable hashtable = new Hashtable();
hashtable.Add("key1", "data1");
hashtable.Add("key2", "data2");
Console.WriteLine(hashtable["key1"]); //displays "data1"
Console.WriteLine(hashtable["key42"]==null); //displays "true"

 

Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("key1", "data1");
dic.Add("key2", "data2");
Console.WriteLine(dic["key1"]); //displays "data1"
Console.WriteLine(dic["key42"]); //throws a KeyNotFoundException

...

Published 26 April 04 11:46


编者或作者:    收录日期: 2008-12-07
参考或来源:

上一页: VB.NET 的参数传递机制 (passing mechanism) 返回上级目录: IT知识文章 下一页: XPath 实例


© 2008 woyouxian.net 版权所有 Contact Us