使用命名空間 (C# 程式設計手冊)Using Namespaces (C# Programming Guide)

C# 程式內大量使用命名空間的原因有兩個。Namespaces are heavily used within C# programs in two ways. 首先,.NET Framework 類別會使用命名空間來組織其多種類別。Firstly, the .NET Framework classes use namespaces to organize its many classes. 其次,宣告您自己的命名空間,有助於在較大型的程式設計專案中控制類別和方法名稱的範圍。Secondly, declaring your own namespaces can help control the scope of class and method names in larger programming projects.

存取命名空間Accessing Namespaces

大部分 C# 應用程式的開頭為 using 指示詞區段。Most C# applications begin with a section of using directives. 本節列出應用程式經常使用的命名空間,並讓程式設計人員每次使用其內包含的方法時不需要指定完整名稱。This section lists the namespaces that the application will be using frequently, and saves the programmer from specifying a fully qualified name every time that a method that is contained within is used.

例如,包含下行:For example, by including the line:

using System;

在程式的開始,程式設計人員可以使用下列程式碼:At the start of a program, the programmer can use the code:

Console.WriteLine("Hello, World!");

而非:Instead of:

System.Console.WriteLine("Hello, World!");

命名空間別名Namespace Aliases

using 指示詞也可以用來建立命名空間的別名。The using Directive can also be used to create an alias for a namespace. 例如,如果您要使用先前撰寫的命名空間以包含巢狀命名空間,則可能想要宣告別名,以特別快速參考別名,如下列範例所示:For example, if you are using a previously written namespace that contains nested namespaces, you might want to declare an alias to provide a shorthand way of referencing one in particular, as in the following example:

using Co = Company.Proj.Nested;  // define an alias to represent a namespace

使用命名空間控制範圍Using Namespaces to control scope

namespace 關鍵字用來宣告範圍。The namespace keyword is used to declare a scope. 在專案內建立範圍的能力有助於組織程式碼,並可讓您建立全域唯一類型。The ability to create scopes within your project helps organize code and lets you create globally-unique types. 在下列範例中,標題為 SampleClass 的類別定義於兩個命名空間中,而其中一個命名空間巢狀於另一個命名空間內。In the following example, a class titled SampleClass is defined in two namespaces, one nested inside the other. 成員存取運算子 . 用來區分呼叫的方法。The member access . operator is used to differentiate which method gets called.

namespace SampleNamespace
{
    class SampleClass
    {
        public void SampleMethod()
        {
            System.Console.WriteLine(
              "SampleMethod inside SampleNamespace");
        }
    }

    // Create a nested namespace, and define another class.
    namespace NestedNamespace
    {
        class SampleClass
        {
            public void SampleMethod()
            {
                System.Console.WriteLine(
                  "SampleMethod inside NestedNamespace");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Displays "SampleMethod inside SampleNamespace."
            SampleClass outer = new SampleClass();
            outer.SampleMethod();

            // Displays "SampleMethod inside SampleNamespace."
            SampleNamespace.SampleClass outer2 = new SampleNamespace.SampleClass();
            outer2.SampleMethod();

            // Displays "SampleMethod inside NestedNamespace."
            NestedNamespace.SampleClass inner = new NestedNamespace.SampleClass();
            inner.SampleMethod();
        }
    }
}

完整名稱Fully Qualified Names

命名空間和類型具有指出邏輯階層之完整名稱所描述的唯一標題。Namespaces and types have unique titles described by fully qualified names that indicate a logical hierarchy. 例如,A.B 陳述式表示 A 是命名空間或類型的名稱,而 B 巢狀於其內。For example, the statement A.B implies that A is the name of the namespace or type, and B is nested inside it.

在下列範例中,有巢狀類別和命名空間。In the following example, there are nested classes and namespaces. 完整名稱會表示為每個實體後面的註解。The fully qualified name is indicated as a comment following each entity.

namespace N1     // N1
{
    class C1      // N1.C1
    {
        class C2   // N1.C1.C2
        {
        }
    }
    namespace N2  // N1.N2
    {
        class C2   // N1.N2.C2
        {
        }
    }
}

在先前的程式碼區段中:In the previous code segment:

  • N1 命名空間是全域命名空間的成員。The namespace N1 is a member of the global namespace. 其完整名稱是 N1Its fully qualified name is N1.

  • N2 命名空間是 N1 的成員。The namespace N2 is a member of N1. 其完整名稱是 N1.N2Its fully qualified name is N1.N2.

  • C1 類別是 N1 的成員。The class C1 is a member of N1. 其完整名稱是 N1.C1Its fully qualified name is N1.C1.

  • 這個程式碼使用類別名稱 C2 兩次。The class name C2 is used two times in this code. 不過,完整名稱是唯一的。However, the fully qualified names are unique. 第一個 C2 執行個體宣告於 C1 內;因此,其完整名稱是 N1.C1.C2The first instance of C2 is declared inside C1; therefore, its fully qualified name is: N1.C1.C2. 第二個 C2 執行個體宣告於 N2 命名空間內;因此,其完整名稱是 N1.N2.C2The second instance of C2 is declared inside a namespace N2; therefore, its fully qualified name is N1.N2.C2.

使用先前的程式碼區段,即可將新的類別成員 C3 新增至命名空間 N1.N2,如下所示:Using the previous code segment, you can add a new class member, C3, to the namespace N1.N2 as follows:

namespace N1.N2
{
    class C3   // N1.N2.C3
    {
    }
}

在一般情況下,使用 :: 來參考命名空間別名,或使用 global:: 參考全域命名空間,以及使用 . 來限定類型或成員。In general, use :: to reference a namespace alias or global:: to reference the global namespace and . to qualify types or members.

搭配使用 :: 與參考型別而非命名空間的別名是錯誤的。It is an error to use :: with an alias that references a type instead of a namespace. 例如:For example:

using Alias = System.Console;
class TestClass
{
    static void Main()
    {
        // Error
        //Alias::WriteLine("Hi");

        // OK
        Alias.WriteLine("Hi");
    }
}

請記住,global 這個單字不是預先定義別名,因此,global.X 沒有任何特殊意義。Remember that the word global is not a predefined alias; therefore, global.X does not have any special meaning. 只有在與 :: 搭配使用時,才會取得特殊意義。It acquires a special meaning only when it is used with ::.

因為 global:: 一律會參考全域命名空間,而不是別名,所以如果您定義名為 global 的別名,就會產生編譯器警告 CS0440。Compiler warning CS0440 is generated if you define an alias named global because global:: always references the global namespace and not an alias. 例如,下行會產生警告:For example, the following line generates the warning:

using global = System.Collections;   // Warning

搭配使用 :: 與別名是不錯的想法,並且可避免非預期導入額外的類型。Using :: with aliases is a good idea and protects against the unexpected introduction of additional types. 例如,請考慮使用以下範例:For example, consider this example:

using Alias = System;
namespace Library
{
    public class C : Alias.Exception { }
}

這會適用,但是如果後續引進名為 Alias 的類型,Alias. 會改為繫結至該類型。This works, but if a type named Alias were to subsequently be introduced, Alias. would bind to that type instead. 使用 Alias::Exception 確保 Alias 視為命名空間別名,而不要被誤認為類型。Using Alias::Exception insures that Alias is treated as a namespace alias and not mistaken for a type.

請參閱主題如何:使用全域命名空間別名,以取得 global 別名的詳細資訊。See the topic How to: Use the Global Namespace Alias for more information regarding the global alias.

另請參閱See also