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

C# 程式設計大量使用命名空間的原因有兩個。Namespaces are heavily used in C# programming in two ways. 首先,.NET Framework 會使用命名空間組織其多種類別,如下所示:First, the .NET Framework uses namespaces to organize its many classes, as follows:

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

System 是命名空間,而 Console 是該命名空間中的類別。System is a namespace and Console is a class in that namespace. 您可以使用 using 關鍵字,如此就不需要完整名稱,如下列範例所示:The using keyword can be used so that the complete name is not required, as in the following example:

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

如需詳細資訊,請參閱 using 指示詞For more information, see the using Directive.

其次,宣告您自己的命名空間,將有助於在較大型的程式設計專案中控制類別和方法名稱的範圍。Second, declaring your own namespaces can help you control the scope of class and method names in larger programming projects. 請使用 namespace 關鍵字宣告命名空間,如下列範例所示:Use the namespace keyword to declare a namespace, as in the following example:

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

命名空間的名稱必須是有效的 C# 識別碼名稱The name of the namespace must be a valid C# identifier name.

命名空間概觀Namespaces Overview

命名空間具有下列屬性:Namespaces have the following properties:

  • 命名空間可組織大型程式碼專案。They organize large code projects.
  • 命名空間會使用 . 運算子分隔。They are delimited by using the . operator.
  • using 指示詞讓您不需要指定每個類別的命名空間名稱。The using directive obviates the requirement to specify the name of the namespace for every class.
  • global 命名空間是「根」命名空間:global::System 一律會參考 .NET System 命名空間。The global namespace is the "root" namespace: global::System will always refer to the .NET System namespace.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格命名空間一節。For more information, see the Namespaces section of the C# language specification.

另請參閱See also