关于Hashtable与Dictionary性能的讨论
Dic是类型安全的,这有助于我们写出更健壮更具可读性的代码,而且省却我们强制转化的麻烦。这个相信大家都明白。
Dic是泛行的,当K或V是值类型时,其速度远远超过Hashtable。
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 类型,所以在存储或检索值类型时
通常发生装箱和取消装箱操作。
HashTable ht=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;
}
//使用索引器来取值时,如果键不存在就会引发异常
try
{
Console.WriteLine("不存在的键""fff""的键值为:" + myDic["fff"]);
}
catch (KeyNotFoundException ex)
{
Console.WriteLine("没有找到键引发异常:" + ex.Message);
}
//解决上面的异常的方法是使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值
string value = "";
if (myDictionary.TryGetValue("fff", out value))
{
Console.WriteLine("不存在的键""fff""的键值为:" + value );
}
else
{
Console.WriteLine("没有找到对应键的键值");
}
//下面用foreach 来遍历键值对
//泛型结构体 用来存储健值对
foreach (KeyValuePair<string, string> temp in myDictionary)
{
Console.WriteLine( temp .Key, temp .Value);
}
//获取值得集合
foreach (string s in myDictionary.Values)
{
Console.WriteLine("value"+ s);
}
//获取值得另一种方式
Dictionary<string, string>.ValueCollection values = myDictionary.Values;
foreach (string s in values)
{
Console.WriteLine("value:"+ s);
}