【问题标题】:Implement IDisposable [duplicate]实施 IDisposable [重复]
【发布时间】:2014-07-01 06:10:54
【问题描述】:

我有以下课程:

public class MyClass : IDisposable
{
   private WebServiceHost m_WebServiceHost;
   // Members
   public void Dispose()
   {
            m_WebServiceHost // how do I dispose this object?
   }
}

WebServiceHost 实现了IDisposable,但它没有Dispose 方法。

如何实现Dispose()

【问题讨论】:

  • IDisposable只有在存在Disposable内容时才需要实现。
  • m_WebServiceHost = null;让 GC 处理?

标签: c# idisposable webservicehost


【解决方案1】:

鉴于它使用explicit interface implementation,我不清楚他们是否希望你这样做,但你可以:

public class MyClass : IDisposable
{
   private WebServiceHost m_WebServiceHost;
   // Members
   public void Dispose()
   {
            ((IDisposable)m_WebServiceHost).Dispose();
   }
}

我会他们更希望你打电话给Close(),但我还不能从文档中备份。

【讨论】:

    【解决方案2】:

    这样做:

    public class MyClass : IDisposable
    {
       private WebServiceHost m_WebServiceHost;
    
       // Often you have to override Dispose method 
       protected virtual void Dispose(Boolean disposing) {
         if (disposing) {
           // It looks that WebServiceHost implements IDisposable explicitly
           IDisposable disp = m_WebServiceHost as IDisposable;
    
           if (!Object.RefrenceEquals(null, disp))
             disp.Dispose();
    
           // May be useful when debugging
           disp = null;       
         }
       }
    
       // Members
       public void Dispose()
       {
         Dispose(true);
         GC.SuppressFinalize(this);
       }
    }
    

    【讨论】:

    • 你应该添加一个调用Dispose(false);的析构函数
    • 这是正确答案,但请解释一下为什么使用 Dispose 模式。
    • disp = null; 似乎是多余的。
    • @thefiloe 不需要。
    • @thefiloe:如果你想派生(来自 MyClass)类,你宁愿有 Dispose(bool)
    猜你喜欢
    • 2013-08-22
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多