Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Tại sao C# không có biến toàn cục (Global Variables)?

C# không có global variables. Toán tử phạm vi (scope resolution operator) trong C++ cho global variables liên quan đến namespaces. Được gọi là global namespace alias.

Nếu có type trùng identifier ở namespace khác, dùng scope resolution operator để phân biệt.

Ví dụ, tham chiếu System.Console class, dùng global namespace alias với scope resolution operator:

global::System.Console

Ví dụ:

Ví dụ

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"); 
            h.Add("O", "3"); 
            h.Add("P", "4"); 
            foreach (string n in h.Keys) { 
                global::System.Console.WriteLine(n + " " + h[n]); 
            } 
        } 
    } 
}

Kết quả

N 2
O 3
M 1
P 4