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

วิธีสร้าง GUID ใน C#

GUID (Globally Unique Identifier) คืออะไร?

ตัวระบุเฉพาะที่ใหญ่โตมาก (128-bit) รับประกันความ Unique ทางคณิตศาสตร์ ไม่ซ้ำกันทั่วระบบ Distributed ทั้งโลก

  • จำนวนค่าที่เป็นไปได้: 3.4 × 10³⁸ ค่า
  • โอกาสซ้ำ: ประมาณ 1 ใน 10³⁰ (Quintillion) แม้สร้าง 10 พันล้าน GUIDs
  • รูปแบบมาตรฐาน: 3F2504E0-4F89-11D3-9A0C-0305E82C3301 (32 Hex digits + 4 Hyphens)

การสร้าง GUID ใน C#

Guid guid = Guid.NewGuid(); // สร้าง GUID ใหม่แบบ Random (Version 4)

ตัวอย่างโค้ดเต็ม

using System;

namespace DemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Guid guid1 = Guid.NewGuid();
            Guid guid2 = Guid.NewGuid();
            
            Console.WriteLine(guid1);
            Console.WriteLine(guid2);
            
            // Parse จาก String
            Guid parsed = Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301");
            Console.WriteLine(parsed);
            
            // Parse แบบปลอดภัย
            if (Guid.TryParse("invalid", out Guid result))
            {
                Console.WriteLine(result);
            }
            
            Console.ReadLine();
        }
    }
}

Output

3a251d82-e8ce-442f-9e42-5285653a5e8a
09081b06-26e2-49fa-8e96-93748a99defa
3f2504e0-4f89-11d3-9a0c-0305e82c3301

GUID Versions และ Method อื่นๆ

MethodVersionคำอธิบาย
Guid.NewGuid()4 (Random)สุ่มทั้งหมด ใช้ทั่วไป
Guid.CreateVersion7()7 (Time-ordered).NET 9+ เรียงตามเวลา ดีสำหรับ DB Index
Guid.Parse()-แปลง String → Guid (Throw ถ้า Invalid)
Guid.TryParse()-แปลงปลอดภัย คืน bool
Guid.Empty-ค่า Zero GUID (0000...)

กรณีใช้งานจริง

  • Primary Key ใน Database (แทน Auto-increment ID)
  • Transaction ID ในระบบ Retail/E-commerce
  • Correlation ID สำหรับ Distributed Tracing
  • File Name ที่ไม่ซ้ำกัน