命名空间(C# 编程指南)Namespaces (C# Programming Guide)

在 C# 编程中,命名空间在两个方面被大量使用。Namespaces are heavily used in C# programming in two ways. 首先,.NET 使用命名空间来组织它的许多类,如下所示:First, .NET 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 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