> For the complete documentation index, see [llms.txt](https://brianwu.gitbook.io/brian/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://brianwu.gitbook.io/brian/brians-za-ji/za-ji/global.md).

# global

參考資料:(<https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/namespaces/how-to-use-the-global-namespace-alias>)

我們平常在寫 `System.Console.WriteLine()`，很正常沒問題。

但如果有一支程式長這樣

```
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()
    {
        // The following line causes an error. It accesses TestApp.Console,
        // which is a constant.
        //Console.WriteLine(number);
    }
}
```

雖然我有`using System;`，但是同一個類別下，已經有被宣告同樣命名為 System 和 Console 的東西，所以本來 `using System;` 的成員就會被隱藏。

即使使用 `System.Console.WriteLine(number);` 也會因為已經有 System，而被隱藏，導致錯誤。

這時可以用 `global` 來暫時解決這個錯誤。

`global::System.Console.WriteLine(number);`

## 當左邊的識別項是 global 的時候，搜尋正確的識別項會從全域命名空間開始。

用以下例子舉例

```
class TestClass : global::TestApp
```

假設我們正在開發A專案，這個專案中已經有一個叫做`TestApp`的命名空間。此時我們想要用B專案的`TestApp`來繼承、改寫。這時我們就要先`using`B專案的`TestApp` ，再用上述方法來繼承。

只要使用`global::`，就會使用上方`using`的命名空間。

## 範例

```
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)
            {
                // Searching the global namespace:
                global::System.Console.WriteLine(name + " " + test[name]);
            }
        }
    }
}
```

`colAlias::Hashtable`會直接去上方的命名空間去找來用。 `global::System.Console.WriteLine`會直接去全域命名空間找來用。

若有相同名稱

`.`會先找近的，遠的會被隱藏。 `::`會去找命名空間的(別名)。可以使用別名。 `global::`會去找全域命名空間的。不可以使用別名。
