Using 与 Try-Finally
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 28 课,共 66 课。
using 语句和 try-finally 代码块都能帮助管理需要妥善释放的资源。using 语句提供了一种更简洁明了的方式,确保妥善清理 IDisposable 对象。
注意:using 可以替代用于释放资源的 try-finally 模式,但不能替代 try-catch。你仍然可以在 try-catch 中包裹 using 块来处理异常。
我们先来看一种 try-finally 方法:
StreamReader reader = null;
try
{
reader = new StreamReader("file.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
using 语句简化了这段代码:
using (StreamReader reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
退出代码块时,using 语句会自动调用 Dispose(),即使发生异常也是如此。
StreamReader 是什么?StreamReader 是一个用于从文件中读取文本的类。你可以通过传入文件名来创建一个 StreamReader,它会打开文件以供读取。它实现了 IDisposable,因此使用后必须正确关闭,而 using 正好可以帮你处理这一点。
常用的 StreamReader 方法:
ReadToEnd():将整个文件读取为一个字符串ReadLine():每次读取一行,到达文件末尾时返回null
要统计文件中的行数,你可以使用 ReadLine() 循环:
using (StreamReader reader = new StreamReader("file.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine(lineCount);
}
你也可以将 using 与 try-catch 结合使用,来处理文件缺失之类的异常:
try
{
using (StreamReader reader = new StreamReader("file.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine(lineCount);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found");
}
挑战
简单创建一个名为 processFile 的方法,它:
- 接收一个文件名作为字符串参数
- 使用
using语句和StreamReader读取文件中的所有行 - 返回文件中的行数
- 如果发生
FileNotFoundException,则打印 "File not found" 并返回 -1
亲手试试
using System;
using System.IO;
class ProcessFile
{
public static int processFile(string filename)
{
// 在这里编写你的代码
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器