您是否可以建议帮助摆脱调用 Initialize() 和 Close() 方法并将其替换为 using 块?
还是这种方法完全可以?
(想法是确保当 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();
}
}