Collections& Genericsมีประโยชน์สำหรับการจัดการกลุ่มวัตถุ ใน .NET, คอลเลกชันทั้งหมดวัตถุมาภายใต้อินเตอร์เฟซIEnumerableซึ่งในทางกลับกันมีและArrayList(Index-Value)) HashTable(Key-Value)หลังจาก .NET Framework 2.0 ArrayListและHashTableถูกแทนที่ด้วยและList Dictionaryตอนนี้Arraylist& HashTableจะไม่ใช้ในโครงการปัจจุบันมากขึ้น
มาถึงความแตกต่างระหว่างHashTable& Dictionary, Dictionaryเป็นทั่วไปในขณะที่Hastableไม่ได้ทั่วไป เราสามารถเพิ่มประเภทของวัตถุใด ๆHashTableแต่ในขณะที่ดึงเราจำเป็นต้องโยนมันลงในประเภทที่ต้องการ ดังนั้นจึงไม่ปลอดภัยพิมพ์ แต่dictionaryในขณะที่ประกาศตัวเองเราสามารถระบุประเภทของคีย์และค่าดังนั้นจึงไม่จำเป็นต้องร่ายขณะดึงข้อมูล
ลองดูตัวอย่าง:
HashTable
class HashTableProgram
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine(Key + " " + value);
}
}
}
พจนานุกรม,
class DictionaryProgram
{
static void Main(string[] args)
{
Dictionary<int, string> dt = new Dictionary<int, string>();
dt.Add(1, "One");
dt.Add(2, "Two");
dt.Add(3, "Three");
foreach (KeyValuePair<int, String> kv in dt)
{
Console.WriteLine(kv.Key + " " + kv.Value);
}
}
}