共用方式為


HOW TO:使用命名空間別名限定詞 (C# 程式設計手冊)

更新:2007 年 11 月

能夠存取全域 namespace 中的成員會十分有用,尤其是該成員可能會被其他同名的實體隱藏的時候。

例如,在下列程式碼中,會將 Console 解析為 TestApp.Console,而不是 System 命名空間中的 Console 型別。

using System;
class TestApp
{
    // Define a new class called 'System' to cause problems.
    public class System { }

    // Define a constant called 'Console' to cause more problems.
    const int Console = 7;
    const int number = 66;

    static void Main()
    {
        // Error  Accesses TestApp.Console
        //Console.WriteLine(number);
    }
}

使用 System.Console 仍會導致錯誤,因為 System 命名空間已被 TestApp.System 類別隱藏:

// Error  Accesses TestApp.System
System.Console.WriteLine(number);

不過,您可以使用 global::System.Console 解決此錯誤,如下所示:

// OK
global::System.Console.WriteLine(number);

當左邊的識別項為 global 時,便會從全域命名空間開始搜尋右邊的識別項。例如,下面的宣告便將 TestApp 當做全域命名空間的成員參考。

class TestClass : global::TestApp

很明顯地,我們並不建議您建立名為 System 的命名空間,而您也不太可能遇到任何發生這種情況的程式碼。不過,在大型專案中,仍很有可能會發生某些形式的命名空間重複。在這種情況下,全域命名空間限定詞即可確保您能夠指定根命名空間。

範例

在這個範例中,命名空間 System 是用於包含類別 TestClass,因此必須使用 global::System.Console 來參考被 System 命名空間隱藏的 System.Console 類別。同樣地,別名 colAlias 是用於參考命名空間 System.Collections,因此,System.Collections.Hashtable 的執行個體是使用這個別名所建立,而不是命名空間。

using colAlias = System.Collections;
namespace System
{
    class TestClass
    {
        static void Main()
        {
            // Searching the alias:
            colAlias::Hashtable test = new colAlias::Hashtable();

            // Add items to the table.
            test.Add("A", "1");
            test.Add("B", "2");
            test.Add("C", "3");

            foreach (string name in test.Keys)
            {
                // Seaching the gloabal namespace:
                global::System.Console.WriteLine(name + " " + test[name]);
            }
        }
    }
}
A 1
B 2
C 3

請參閱

概念

C# 程式設計手冊

參考

命名空間 (C# 程式設計手冊)

. 運算子 (C# 參考)

:: 運算子 (C# 參考)

extern (C# 參考)