C中using语句与命名空间的深入解析
立即解锁
发布时间: 2025-08-21 00:06:06 阅读量: 2 订阅数: 8 


C#编程基础与实战技巧
### C# 中 using 语句与命名空间的深入解析
#### 1. using 语句的使用示例
在 C# 编程里,`using` 语句是管理资源的有力工具。它能确保实现了 `IDisposable` 接口的对象在使用完毕后,其 `Dispose` 方法被调用,从而正确释放资源。下面是一个 `using` 语句的使用示例:
```csharp
using System; // using DIRECTIVE; not using statement
using System.IO; // using DIRECTIVE; not using statement
namespace UsingStatement
{
class Program
{
static void Main()
{
// using statement
using (TextWriter tw = File.CreateText("Lincoln.txt") )
{
tw.WriteLine("Four score and seven years ago, ...");
}
// using statement
using (TextReader tr = File.OpenText("Lincoln.txt"))
{
string InputString;
while (null != (InputString = tr.ReadLine()))
Console.WriteLine(InputString);
}
}
}
}
```
此代码运用 `using` 语句两次,一次针对 `TextWriter` 类,另一次针对 `TextReader` 类,这两个类都来自 `System.IO` 命名空间。`TextWriter` 资源开启一个文本文件用于写入操作,并向文件写入一行内容;`TextReader` 资源接着开启同一个文本文件,逐行读取并显示其内容。在这两种情形下,`using` 语句都保证了对象的 `Dispose` 方法被调用。
#### 2. 多资源与嵌套使用 using 语句
`using` 语句还能用于处理同一类型的多个资源,资源声明之间用逗号分隔,语法如下:
```plaintext
using ( ResourceType Id1 = Expr1, Id2 = Expr2, ... ) EmbeddedStatement
```
以下代码展示了每个 `using` 语句分配并使用两个资源的情况:
```csharp
static void Main()
{
using (TextWriter tw1 = File.CreateText("Lincoln.txt"),
tw2 = File.CreateText("Franklin.txt"))
{
tw1.WriteLine("Four score and seven years ago, ...");
tw2.WriteLine("Early to bed; Early to rise ...");
}
using (TextReader tr1 = File.OpenText("Lincoln.txt"),
tr2 = File.OpenText("Franklin.txt"))
{
string InputString;
while (null != (InputString = tr1.ReadLine()))
Console.WriteLine(InputString);
while (null != (InputString = tr2.ReadLine()))
Console.WriteLine(InputString);
}
}
```
`using` 语句也可以嵌套使用。在下面的代码中,除了 `using` 语句的嵌套,还需注意第二个 `using` 语句由于仅包含一条简单语句,所以无需使用代码块:
```csharp
using ( TextWriter tw1 = File.CreateText("Lincoln.txt") )
{
tw1.WriteLine("Four score and seven years ago, ...");
using ( TextWriter tw2 = File.CreateText("Franklin.txt") ) // Nested
tw2.WriteLine("Early to bed; Early to rise ..."); // Single
}
```
#### 3. using 语句的另一种形式
`using` 语句还有另一种形式:
```plaintext
using ( Expression ) EmbeddedStatement
```
在这种形式中,资源在 `using` 语句之前声明。示例如下:
```csharp
TextWriter tw = File.CreateText("Lincoln.txt"); // Resource declared
using ( tw ) // using statement
tw.WriteLine("Four score and seven years ago, ...");
```
尽管这种形式仍能确保在使用完资源后调用 `Dispose` 方法,但它无法防止在 `using` 语句释放非托管资源后尝试使用该资源,从而使资源处于不一致状态。因此,这种形式提供的保护较少,不建议使用。
#### 4. 其他相关语句
除了 `using` 语句,还有一些与语言特定特性相关的语句,如下表所示:
| 语句 | 描述 |
| ---- | ---- |
| checked, unchecked | 这些语句控制溢出检查上下文 |
| foreach | 该语句用于遍历集合中的每个成员 |
| try, throw, finally | 这些语句与异常处理相关 |
| return | 此语句将控制权返回给调用函数成员,还能返回一个值 |
| yield | 该语句用于迭代器 |
#### 5. 引用其他程序集
在许多项目中,我们常常需要使用其他程序集中的类或类型。这些程序集可能来自 BCL(基础类库)、第三方供应商,或者是我们自己创建的。这些被称为类库,其程序集文件的名称通常以 `.dll` 扩展名
0
0
复制全文
相关推荐










