Man*_*oon 5 c# using filestream
通常,"使用"是正确访问和处理文件流的优选方法.
我经常需要打开文件(如下所示).在这种情况下可以采用"使用"结构吗?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
是的,你制作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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1006 次 |
| 最近记录: |