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

ทำไม C# จึงไม่มีตัวแปร Global

เหตุผลที่ C# ไม่มีตัวแปร Global

C# เป็นภาษาที่ออกแบบมาให้เป็น Object-Oriented อย่างสมบูรณ์ ไม่มีแนวคิด "ตัวแปรระดับโมดูล" หรือ "ตัวแปร Global" แบบดั้งเดิม (เช่นใน C/C++) ทุกตัวแปรต้องอยู่ภายใน ประเภท (Type) เช่น class, struct, record

เหตุผลหลัก

  • Encapsulation: ข้อมูลและพฤติกรรมอยู่ร่วมกันในออบเจกต์
  • Namespace Isolation: ใช้ namespace แยกชื่อแทน global scope
  • Thread Safety: Global state ทำให้ multi-threading ยากต่อการจัดการ
  • Testability: Global state ทำให้ Unit Testing ยาก (shared state)
  • Maintainability: ลด coupling ระหว่างส่วนต่างๆ ของโปรแกรม

ตัวเลือกแทน Global Variables

1. Static Class (Singleton Pattern)

public static class AppSettings
{
    public static string ConnectionString { get; set; }
    public static int MaxRetryCount { get; set; } = 3;
}

// ใช้งาน
AppSettings.ConnectionString = "Server=...";

2. Dependency Injection (แนะนำ)

public interface IConfiguration
{
    string ConnectionString { get; }
}

public class AppConfig : IConfiguration
{
    public string ConnectionString { get; } = "Server=...";
}

// ลงทะเบียนใน DI container แล้ว inject ไปยังคลาสที่ต้องการ

3. Module Initializers (C# 9+)

internal static class ModuleInitializer
{
    [ModuleInitializer]
    public static void Initialize()
    {
        // รันก่อนทุกอย่างใน assembly
        Console.WriteLine("Module initialized");
    }
}

Global Namespace Alias (::)

C# มี global:: สำหรับอ้างอิง root namespace เมื่อมีชื่อชนกัน:

namespace MyApp
{
    class Console { } // ชนกับ System.Console
}

class Program
{
    static void Main()
    {
        // ใช้ global:: เพื่อระบุ System.Console จริง
        global::System.Console.WriteLine("Hello");
    }
}

ตัวอย่างจากโค้ดต้นฉบับ

using myAlias = System.Collections;

namespace Program
{
    class Demo
    {
        static void Main()
        {
            myAlias::Hashtable h = new myAlias::Hashtable();
            h.Add("M", "1");
            h.Add("N", "2");
            
            // ใช้ global::System.Console
            foreach (string n in h.Keys)
            {
                global::System.Console.WriteLine(n + " " + h[n]);
            }
        }
    }
}

สรุป

C# ไม่มี global variables โดยเจตนา เพื่อส่งเสริมการออกแบบที่ดีกว่า ใช้ Static classes, Dependency Injection, หรือ Singleton pattern แทน ซึ่งให้การควบคุม ทดสอบ และบำรุงรักษาที่ดีกว่า