Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ดึงหรือตั้งค่าที่เกี่ยวข้องกับคีย์ใน Hashtable ใน C#

ภาพรวม

Hashtable รองรับการเข้าถึงค่าผ่านคีย์ด้วยดัชนี hash[key] ใช้ได้ทั้งการอ่าน (get) และการเขียน/อัปเดต (set)

ตัวอย่างที่ 1: ดึงค่าด้วยคีย์

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable();
        hash.Add("1", "AB");
        hash.Add("2", "BC");
        hash.Add("3", "DE");
        hash.Add("4", "EF");
        hash.Add("5", "GH");
        hash.Add("6", "IJ");
        hash.Add("7", "KL");
        hash.Add("8", "MN");
        hash.Add("9", "OP");
        hash.Add("10", "QR");
        Console.WriteLine("Value at key 3 = " + hash["3"]);
    }
}

ผลลัพธ์

Value at key 3 = DE

ตัวอย่างที่ 2: ดึงและอัปเดตค่า

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable();
        hash.Add("1", "AB");
        hash.Add("2", "BC");
        hash.Add("3", "DE");
        hash.Add("4", "EF");
        hash.Add("5", "GH");
        hash.Add("6", "IJ");
        hash.Add("7", "KL");
        hash.Add("8", "MN");
        hash.Add("9", "OP");
        hash.Add("10", "QR");
        Console.WriteLine("Value at key 3 = " + hash["3"]);
        hash["3"] = "UV";
        Console.WriteLine("Value at key 3 (UPDATED) = " + hash["3"]);
    }
}

ผลลัพธ์

Value at key 3 = DE
Value at key 3 (UPDATED) = UV

คำอธิบายเพิ่มเติม

  • การ get คีย์ที่ไม่มีอยู่ คืนค่า null (ไม่โยนข้อยกเว้น)
  • การ set คีย์ที่ไม่มีอยู่ จะเพิ่มคู่คีย์-ค่าใหม่ (เทียบเท่า Add)
  • Hashtable ยอมรับคีย์และค่าเป็น object (non-generic) ต้องแปลงชนิด (cast) เมื่อใช้งาน
  • สำหรับโค้ดใหม่ ใช้ Dictionary<TKey, TValue> เพื่อ type safety และประสิทธิภาพดีกว่า