2011-03-03 89 views
5

Dictionary和Hashtable有什么区别?我该如何得出使用哪个结论?任何人都可以帮助我吗?Dictionary和Hashtable之间的主要区别是什么

+3

http://stackoverflow.com/questions/301371/why-dictionary-is-preferred-over-hashtable-in-c – Douglas 2011-03-03 09:42:58

+0

查看下面类似的问题:http://stackoverflow.com/questions/1089132/net- hashtable-vs-dictionary-can-the-dictionary-as-as-fast – 2011-03-03 09:43:04

回答

1

散列表已过时。总是使用词典。

1

我在哈希表新手太多,但...

字典是具有两列的基本表(Key和Value,既具有某些类型)和大量的行以后添加。你会看到,在字典中你给一个关键字和字典给你以前用完全相同的键添加的价值。

在散列表中的东西稍有不同。你有两列的表(键和值,都是“对象”类型)。密钥可能不是唯一的。现在你虚拟有两个表:一列有两列:键和散列,另一列有两列哈希和值。哈希是从Key得到的一些整数值。事实证明,尽管Keys可能是唯一的,但Hashes可能不是。 [但我不知道这...所以我说:“virtualy” ...]

现在,例如:

Hashtable ht = new Hashtable(); 
// Key of type Int32 
ht[16] = "That is Int32"; 
// Key of type String 
ht["Blah"] = 15; 
// Key of type Boolean 
ht[false] = "That is boolean"; 
// Key of type String 
ht["Hohoho"] = false; 

,以后你可以访问存储在Hashtable中只使用密钥的任何值(如果没有这样的键返回null):

Console.WriteLine("ht[{0}] = {1};", 16, ht[16] ?? "null"); 
Console.WriteLine("ht[{0}] = {1};", "Test", ht["Test"] ?? "null"); // doesnt exist eh... 
Console.WriteLine("ht[{0}] = {1};", false, ht[false] ?? "null"); 
Console.WriteLine("ht[{0}] = {1};", "Hohoho", ht["Hohoho"] ?? "null"); 

要sumarize:

字典是这样的:

[ Key ][ Value ] 
    A  1.5 
    B  1.6 
    C  -8 
    .... 

和Hashtable probabily是这样的:

[ Key ][ Hash ] 
    A  1 
    B  2 
    C  -99 
     ... 

[ Hash ][ Value ] 
    -99  -8 
    1  1.6 
    2  1.5 
     .... 

我希望这是任何有帮助的。任何人都可以更好地解释它,毫不犹豫地这样做。

谢谢,祝你好运。

相关问题