【发布时间】:2010-12-03 06:00:09
【问题描述】:
在 C# 迭代器块中有什么方法可以提供一个代码块,该代码块将在 foreach 结束时运行(或者自然地被中断),比如清理资源?
我想出的最好方法是使用 using 构造,这很好,但确实需要一个 IDisposable 类来进行清理。例如:
public static IEnumerable<string> ReadLines(this Stream stream)
{
using (StreamReader rdr = new StreamReader(stream))
{
string txt = rdr.ReadLine();
while (txt != null)
{
yield return txt;
txt = rdr.ReadLine();
}
rdr.Close();
}
}
【问题讨论】: