pen*_*ake 0 .net c# idisposable using-statement streamwriter
你有没有办法建议帮助摆脱调用Initialize()和Close()方法并将其替换为使用块?
或者这种方法完全没问题?
(想法是确保当FooWriter的消费者写下一些字符串并完成此操作时将处理Writer.)
class Program
{
static void Main(string[] args)
{
var writer = new FooWriter();
writer.Initialize();
foreach (var s in args)
writer.Write(s);
writer.Cose();
}
public class FooWriter
{
public StreamWriter Writer;
public void Initialize()
{
Writer = new StreamWriter("MyFile.txt", false);
}
public void Write(string line)
{
if(Writer==null)
throw new NullReferenceException(Writer, "Writer"); // Guard Writer
Writer.WriteLine(line);
}
public void Close()
{
Writer.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过你做FooWriter
的IDisposable
.并将初始化移动到其构造函数中:
public class FooWriter : IDisposable {
public StreamWriter Writer;
public FooWriter()
{
Writer = new StreamWriter("MyFile.txt", false);
}
public void Write(string line)
{
// You do not need to guard the writer, because constructor sets it
if(Writer==null)
throw new NullReferenceException(Writer, "Writer"); // Guard Writer
Writer.WriteLine(line);
}
public void Dispose()
{
Writer.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
96 次 |
最近记录: |