C# 学习笔记 - 2.1 - 命名空间

发布时间 2023-08-21 20:26:11作者: Snoopy1866

命名空间

命名空间的存在是为了解决编译器无法处理的重名问题。举个例子:如果没有命名空间,你将无法创建一个名为 Console 的类,因为 .NET 已经在 System 命名空间中使用了这个名称。

命名空间采用如下方式进行定义:

namespace MyApplication
 {
     // The content to reside in the MyApplication namespace is placed here.
 }

.NET Framework 提供了一个完整的命名空间层次结构,其中 System 通常是最常用的命名空间,命名空间内的数据是通过 . 操作符来引用的,例如:

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

以上代码将会调用 System 命名空间中的 Console 类的 WriteLine 方法。

使用 using 关键字显式声明程序将会使用到的命名空间,后续引用命名空间中的元素时,可以不指定命名空间,编译器会自动在命名空间中查找对应元素,例如:

using System;
 
 namespace MyApplication
 {
   class MyClass
   {
     void ShowGreeting()
     {
         Console.WriteLine("Hello, World!"); // note how System is now not required
     }
   }
 }

命名空间是全局的,因此,一个 C# 源文件中的命名空间,和另一个 C# 源文件中的同名命名空间,其实是同一个命名空间,编译器会将两个同名命名空间下的元素视为同一命名空间下的元素。

Namespaces are global, so a namespace in one C# source file, and another with the same name in another source file, will cause the compiler to treat the different named information in these two source files as residing in the same namespace.

嵌套命名空间

命名空间可以嵌套,即可以在一个命名空间内部定义另一个命名空间,例如:

namespace CodeWorks
 {
     namespace MyApplication
     {
         // Do stuff
     }
 }

或者,也可以这样定义:

 namespace CodeWorks.MyApplication
 {
     // Do stuff
 }