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

Global และ Local Variables ใน C# - Scope และ Namespace Alias

C# มี Variable Scope ที่ชัดเจน: Local Variable (ใน Method/Block) และไม่มี Global Variable ตรงๆ แต่ใช้ Namespace Alias และ global:: สำหรับ Name Resolution

Local Variables

ประกาศภายใน Method/Block ใช้ได้เฉพาะใน Scope นั้น

using System;

public class Program
{
    public static void Main()
    {
        int a = 100;           // Local Variable
        string message = "Hello"; // Local Variable

        if (true)
        {
            int b = 200;       // Block-scoped Local
            Console.WriteLine(b); // OK
        }
        // Console.WriteLine(b); // Error: b ไม่อยู่ใน Scope

        Console.WriteLine(a);  // OK
    }
}

ไม่มี Global Variable ตรงๆ

C# ไม่รองรับ Global Variable แบบ C/C++ (ตัวแปรนอก Class/Struct) ทุกตัวแปรต้องอยู่ใน Type (Class/Struct/Record)

Static Fields - ใกล้เคียง Global มากที่สุด

public class AppConfig
{
    // "Global" Accessible ทุกที่ผ่าน Class Name
    public static string ConnectionString { get; set; }
    public static int MaxRetryCount { get; set; } = 3;
}

// ใช้งาน
AppConfig.ConnectionString = "Server=...";
var conn = AppConfig.ConnectionString;

Namespace Alias (using alias)

แก้ไข Naming Conflict ระหว่าง Namespace

// Alias สำหรับ Namespace
using MyCollections = System.Collections.Generic;
using Legacy = MyCompany.OldLibrary;

// ใช้งาน
MyCollections.List list = new MyCollections.List();
Legacy.SomeClass obj = new Legacy.SomeClass();

global:: Namespace Alias

บังคับให้เริ่ม Resolve จาก Global Namespace Root


// ปัญหา: มี Class ชื่อ Console ใน Project
class Console { } // ซ้ำกับ System.Console

// แก้: ใช้ global::
global::System.Console.WriteLine("Real Console");

// หรือ Alias
using RealConsole = global::System.Console;
RealConsole.WriteLine("Real Console");

ตัวอย่างเต็มจากต้นฉบับ (Fixed)

using MyAlias = System.Collections; // Alias Namespace

namespace Program
{
    class Demo
    {
        static void Main()
        {
            // ใช้ Alias
            MyAlias.Hashtable hTable = new MyAlias.Hashtable();
            hTable.Add("A", "1");
            hTable.Add("B", "2");
            hTable.Add("C", "3");

            foreach (string key in hTable.Keys)
            {
                // ใช้ global:: เพื่อระบุ System.Console จริง
                global::System.Console.WriteLine($"{key} {hTable[key]}");
            }
        }
    }
}

Best Practices

  • หลีกเลี่ยง Static Mutable State (Global-like) - ทำให้ Test/Yield ยาก
  • ใช้ Dependency Injection แทน Static Properties
  • Constants (const/static readonly) ปลอดภัยกว่าเพราะ Immutable
  • Thread Safety: Static Fields ต้อง Lock เองหรือใช้ Concurrent Collections

สรุป

ประเภทScopeLifetimeเข้าถึง
Local VariableMethod/BlockDuring Executionใน Scope เดียว
Instance FieldObject InstanceObject Lifetimeผ่าน Instance
Static FieldAppDomain/ProcessProcess LifetimeClassName.Field (Global-like)
ConstCompile-timeProcess LifetimeClassName.Const (Global-like)