命名空间(C# 参考)namespace (C# Reference)

namespace 关键字用于声明包含一组相关对象的作用域。The namespace keyword is used to declare a scope that contains a set of related objects. 可以使用命名空间来组织代码元素并创建全局唯一类型。You can use a namespace to organize code elements and to create globally unique types.

namespace SampleNamespace
{
    class SampleClass { }

    interface ISampleInterface { }

    struct SampleStruct { }

    enum SampleEnum { a, b }

    delegate void SampleDelegate(int i);

    namespace Nested
    {
        class SampleClass2 { }
    }
}

备注Remarks

在命名空间中,可以声明零个或多个以下类型:Within a namespace, you can declare zero or more of the following types:

无论是否在 C# 源文件中显式声明命名空间,编译器都会添加一个默认命名空间。Whether or not you explicitly declare a namespace in a C# source file, the compiler adds a default namespace. 此未命名的命名空间(有时被称为全局命名空间)存在于每个文件中。This unnamed namespace, sometimes referred to as the global namespace, is present in every file. 全局命名空间中的任何标识符都可用于已命名的命名空间。Any identifier in the global namespace is available for use in a named namespace.

命名空间隐式具有公共访问权限,这是不可修改的。Namespaces implicitly have public access and this is not modifiable. 有关可以分配给命名空间中元素的访问修饰符的讨论,请参阅访问修饰符For a discussion of the access modifiers you can assign to elements in a namespace, see Access Modifiers.

可以在两个或多个声明中定义一个命名空间。It is possible to define a namespace in two or more declarations. 例如,以下示例将两个类定义为 MyCompany 命名空间的一部分:For example, the following example defines two classes as part of the MyCompany namespace:

namespace MyCompany.Proj1
{
    class MyClass
    {
    }
}

namespace MyCompany.Proj1
{
    class MyClass1
    {
    }
}

示例Example

以下示例显示如何在嵌套命名空间中调用静态方法。The following example shows how to call a static method in a nested namespace.

namespace SomeNameSpace
{
    public class MyClass 
    {
        static void Main() 
        {
            Nested.NestedNameSpaceClass.SayHello();
        }
    }

    // a nested namespace
    namespace Nested   
    {
        public class NestedNameSpaceClass 
        {
            public static void SayHello() 
            {
                Console.WriteLine("Hello");
            }
        }
    }
}
// Output: Hello

有关使用命名空间的详细信息,请参阅以下主题:For more information about using namespaces, see the following topics:

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also