一般来说,"使用"是正确访问和处理文件流的首选方法。
我经常需要打开文件(如下所示)。可以"使用"在这种情况下应该采用哪种结构?
public class logger
{
private StreamWriter sw;
public logger(string fileName)
{
sw = new StreamWriter(fileName, true);
}
public void LogString(string txt)
{
sw.WriteLine(txt);
sw.Flush();
}
public void Close()
{
sw.Close();
}
}
答案 0 :(得分:5)
是的,你使Logger
是一次性的,并让它在处置方法中处理流。
// I make it sealed so you can use the "easier" dispose pattern, if it is not sealed
// you should create a `protected virtual void Dispose(bool disposing)` method.
public sealed class logger : IDisposable
{
private StreamWriter sw;
public logger(string fileName)
{
sw = new StreamWriter(fileName, true);
}
public void LogString(string txt)
{
sw.WriteLine(txt);
sw.Flush();
}
public void Close()
{
sw.Close();
}
public void Dispose()
{
if(sw != null)
sw.Dispose();
}
}