个性化阅读
专注于IT技术分析

C#中的Hashtable和Dictionary有什么区别?

点击下载

在C#中, Dictionary是通用集合, 通常用于存储键/值对。字典的定义如下System.Collection.Generics命名空间。它本质上是动态的, 这意味着字典的大小会根据需要而增加。

例子:

//C# program to illustrate Dictionary
using System;
using System.Collections.Generic;
  
class GFG {
  
     //Main Method
     static public void Main()
     {
  
         //Creating a dictionary
         //using Dictionary<TKey, TValue> class
         Dictionary<string , string> My_dict = 
                     new Dictionary<string , string>();
  
         //Adding key/value pairs in the Dictionary
         //Using Add() method
         My_dict.Add( "a.01" , "C" );
         My_dict.Add( "a.02" , "C++" );
         My_dict.Add( "a.03" , "C#" );
  
         foreach (KeyValuePair<string , string> element in My_dict)
         {
             Console.WriteLine( "Key:- {0} and Value:- {1}" , element.Key, element.Value);
         }
     }
}

输出如下:

Key:- a.01 and Value:- C
Key:- a.02 and Value:- C++
Key:- a.03 and Value:- C#

哈希表是基于键的哈希码排列的键/值对的集合。换句话说, 哈希表用于创建使用哈希表进行存储的集合。这是非通用类型的集合, 在系统集合命名空间。在哈希表中, 键对象必须是不可变的, 只要它们在哈希表中用作键即可。

例子:

//C# program to illustrate a hashtable
using System;
using System.Collections;
  
class GFG {
  
     //Main method
     static public void Main()
     {
  
         //Create a hashtable
         //Using Hashtable class
         Hashtable my_hashtable = new Hashtable();
  
         //Adding key/value pair in the hashtable
         //Using Add() method
         my_hashtable.Add( "A1" , "Welcome" );
         my_hashtable.Add( "A2" , "to" );
         my_hashtable.Add( "A3" , "srcmini" );
  
         foreach (DictionaryEntry element in my_hashtable)
         {
             Console.WriteLine( "Key:- {0} and Value:- {1} " , element.Key, element.Value);
         }
     }
}

输出如下:

Key:- A3 and Value:- srcmini 
Key:- A2 and Value:- to 
Key:- A1 and Value:- Welcome

哈希表与字典

哈希表 字典
哈希表是一个非泛型集合。 字典是通用集合。
哈希表在System.Collections命名空间下定义。 字典在System.Collections.Generic命名空间下定义。
在哈希表中, 你可以存储相同类型或不同类型的键/值对。 在字典中, 你可以存储相同类型的键/值对。
在哈希表中, 无需指定键和值的类型。 在字典中, 你必须指定键和值的类型。
由于装箱/拆箱, 数据检索比字典慢。 由于没有装箱/拆箱, 数据检索比哈希表更快。
在哈希表中, 如果你尝试访问给定哈希表中不存在的键, 则它将提供空值。 在”词典”中, 如果你尝试访问给定词典中不存在的键, 则会出现错误。
这是线程安全的。 它也是线程安全的, 但仅适用于公共静态成员。
它不会保持存储值的顺序。 它始终保持存储值的顺序。

赞(0)
未经允许不得转载:srcmini » C#中的Hashtable和Dictionary有什么区别?

评论 抢沙发

评论前必须登录!