在C#中,命名空间(Namespace)是一种用于将大量的类、结构体、枚举、接口、委托以及其他命名空间组织到一起的方式,有助于避免命名冲突,方便代码的组织和管理。
在.NET框架中,命名空间按照一个分层的方式进行组织。比如,System.Collections.Generic
命名空间就代表这样的一个层级结构:最顶层是System
命名空间,它包含一个名为Collections
的子命名空间,而Collections
命名空间又包含一个名为Generic
的子命名空间。在Generic
命名空间中,我们可以找到如List<T>
、Dictionary<TKey, TValue>
等常用的集合类。
在C#代码中,我们使用using
关键字来引入命名空间,这样在该文件中就可以直接使用该命名空间中的类型,而无需完全限定名。比如:
using System;
using System.Collections.Generic;
public class Example
{
public void PrintNumbers(List<int> numbers)
{
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
在这个例子中,我们引入了System
和System.Collections.Generic
两个命名空间,所以可以直接使用Console
和List<T>
这两个类型,而无需写成System.Console
和System.Collections.Generic.List<T>
。