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

ดึงหรือตั้งค่าใน StringDictionary ด้วยคีย์ที่ระบุใน C#

ภาพรวม

StringDictionary ใน namespace System.Collections.Specialized เป็นดิกชันนารีที่ออกแบบมาสำหรับเก็บคีย์และค่าเป็นสตริงเท่านั้น (strongly-typed string dictionary) รองรับการเข้าถึงผ่านดัชนี (indexer) คล้าย HybridDictionary

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

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringDictionary myDict = new StringDictionary();
        myDict.Add("1", "Tablet");
        myDict.Add("2", "Desktop");
        myDict.Add("3", "Speakers");
        myDict.Add("4", "Laptop");
        myDict.Add("5", "Notebook");
        myDict.Add("6", "Ultrabook");
        myDict.Add("7", "HDD");
        myDict.Add("8", "SDD");
        myDict.Add("9", "Headphone");
        myDict.Add("10", "Earphone");
        Console.WriteLine("Value for key 5 = " + myDict["5"]);
    }
}

ผลลัพธ์

Value for key 5 = Notebook

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

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringDictionary myDict = new StringDictionary();
        myDict.Add("1", "Tablet");
        myDict.Add("2", "Desktop");
        myDict.Add("3", "Speakers");
        myDict.Add("4", "Laptop");
        myDict.Add("5", "Notebook");
        myDict.Add("6", "Ultrabook");
        myDict.Add("7", "HDD");
        myDict.Add("8", "SDD");
        myDict.Add("9", "Headphone");
        myDict.Add("10", "Earphone");
        Console.WriteLine("Value for key 5 = " + myDict["5"]);
        myDict["5"] = "Flash Drive";
        Console.WriteLine("Value for key 5 [Updated] = " + myDict["5"]);
    }
}

ผลลัพธ์

Value for key 5 = Notebook
Value for key 5 [Updated] = Flash Drive

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

  • StringDictionary บังคับให้คีย์และค่าเป็นชนิด string เท่านั้น ช่วยลดข้อผิดพลาดในการเขียนโค้ด
  • คีย์จะถูกแปลงเป็นตัวพิมพ์เล็ก (case-insensitive) อัตโนมัติภายใน
  • เหมาะสำหรับการเก็บการตั้งค่า (settings), หัวข้อ HTTP headers, หรือข้อมูลคอนฟิกที่เป็นข้อความ
  • คลาสนี้ถือว่าเป็น legacy (เก่า) สำหรับโครงการใหม่แนะนำให้ใช้ Dictionary<string, string> แทน