0

您是否可以建议帮助摆脱调用 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();
    }

}
4

3 回答 3

5

您可以通过制作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();
    }

}
于 2012-10-29T12:59:11.957 回答
1

你可以让 FooWriter 实现 IDisposable 并在构造函数中调用 Initialize() ,然后你可以使用 at 如下:

class FooWriter : IDisposable
{
   private StreamWriter Writer;
   public FooWriter()
   {
      Writer = new StreamWriter("MyFile.txt", false);
   }
   public void Write(string line)
   {
     Writer.WriteLine(line);
   }
   public void Dispose()
   {
        Writer.Dispose();
   }
}


// use it

using (var writer = new FooWriter())
{
  foreach (var s in args)
                writer.Write(s);
}
于 2012-10-29T13:01:44.850 回答
1

我会像这样改变你的实现:

  • 使类实现 IDisposable
  • 在构造函数中初始化编写器
  • 删除异常

    公共类 FooWriter : IDisposable { public StreamWriter Writer { get; 私人套装;}

    public FooWriter(string fileName)
    {
        Writer = new StreamWriter(fileName, false);
    }
    
    public void Write(string line)
    {                        
        Writer.WriteLine(line);
    }      
    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    
    protected virtual void Dispose(bool disposeManaged)
    {
        if (disposeManaged)
            Writer.Dispose();
    }
    

    }

于 2012-10-29T13:02:55.087 回答