- C# 基础教程
- C# - 首页
- C# - 概述
- C# - 环境
- C# - 程序结构
- C# - 基本语法
- C# - 数据类型
- C# - 类型转换
- C# - 变量
- C# - 常量
- C# - 运算符
- C# - 决策
- C# - 循环
- C# - 封装
- C# - 方法
- C# - 可空类型
- C# - 数组
- C# - 字符串
- C# - 结构体
- C# - 枚举
- C# - 类
- C# - 继承
- C# - 多态
- C# - 运算符重载
- C# - 接口
- C# - 命名空间
- C# - 预处理器指令
- C# - 正则表达式
- C# - 异常处理
- C# - 文件 I/O
- C# 高级教程
- C# - 属性
- C# - 反射
- C# - 属性
- C# - 索引器
- C# - 委托
- C# - 事件
- C# - 集合
- C# - 泛型
- C# - 匿名方法
- C# - 不安全代码
- C# - 多线程
- C# 有用资源
- C# - 问题与解答
- C# - 快速指南
- C# - 有用资源
- C# - 讨论
C# - 命名空间
命名空间旨在提供一种方法来使一组名称与另一组名称分开。在一个命名空间中声明的类名不会与在另一个命名空间中声明的相同类名冲突。
定义命名空间
命名空间定义以关键字namespace开头,后跟命名空间名称,如下所示:
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类就在其中定义。我们只需编写:
Console.WriteLine ("Hello there");
我们也可以写出完全限定名,如下所示:
System.Console.WriteLine("Hello there");
您还可以使用using命名空间指令避免在命名空间前添加前缀。此指令告诉编译器后续代码正在使用指定命名空间中的名称。因此,命名空间对于后续代码是隐含的:
让我们使用 using 指令重写前面的示例:
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
广告