无涯教程-C# - 命名空间

115 阅读2分钟

命名空间旨在提供一种将一组名称与另一组名称分开的方法,在一个命名空间中声明的类名与在另一个命名空间中声明的相同类名不冲突。

定义命名空间

命名空间定义以关键字命名空间开头,后跟命名空间名称,如下所示:-

namespace namespace_name {
   //code declarations
}

要调用函数或变量的命名空间,请将命名空间名称作为前缀,如下所示-

namespace_name.item_name;

以下程序演示了命名空间的使用

using System;

namespace first_space { class namespace_cl { public void func() { Console.WriteLine("Inside first_space"); } } } namespace second_space { class namespace_cl { public void func() { Console.WriteLine("Inside second_space"); } } } class TestClass { static void Main(string[] args) { first_space.namespace_cl fc = new first_space.namespace_cl(); second_space.namespace_cl sc = new second_space.namespace_cl(); fc.func(); sc.func(); Console.ReadKey(); } }

编译并执行上述代码时,将生成以下输出-

Inside first_space
Inside second_space

using 关键字

using关键字声明程序正在使用给定命名空间中的名称,例如,无涯教程在程序中使用System命名空间,类Console是从System那里定义的。只是写-

Console.WriteLine ("Hello there");

可以编写全路径形式-

System.Console.WriteLine("Hello there");

您还可以避免将using namespace指令作为命名空间的前缀,此指令告诉编译器后续代码正在使用指定命名空间中的名称。

using System;
using first_space;
using second_space;

namespace first_space { class abc { public void func() { Console.WriteLine("Inside first_space"); } } } namespace second_space { class efg { public void func() { Console.WriteLine("Inside second_space"); } } }
class TestClass { static void Main(string[] args) { abc fc = new abc(); efg sc = new efg(); fc.func(); sc.func(); Console.ReadKey(); } }

编译并执行上述代码时,将生成以下输出-

Inside first_space
Inside second_space

嵌套命名空间

您可以在另一个命名空间内定义一个命名空间,如下所示-

namespace namespace_name1 {

//code declarations namespace namespace_name2 { //code declarations } }

可以使用点(.)访问嵌套命名空间的成员运算符如下-

using System;
using first_space;
using first_space.second_space;

namespace first_space { class abc { public void func() { Console.WriteLine("Inside first_space"); } } namespace second_space { class efg { public void func() { Console.WriteLine("Inside second_space"); } } }
} class TestClass { static void Main(string[] args) { abc fc = new abc(); efg sc = new efg(); fc.func(); sc.func(); Console.ReadKey(); } }

编译并执行上述代码时,将生成以下输出-

Inside first_space
Inside second_space

参考链接

www.learnfk.com/csharp/csha…