【问题标题】:How does this class implement IDisposable if it doesn't have a Dispose method?如果这个类没有 Dispose 方法,它如何实现 IDisposable?
【发布时间】:2011-03-08 07:49:59
【问题描述】:

FtpWebResponse 实现了 IDisposable,但它没有 Dispose 方法。这怎么可能?

【问题讨论】:

    标签: c# interface idisposable ftpwebresponse


    【解决方案1】:

    【讨论】:

    • 我也没有看到任何 Dispose 方法。
    • 向下滚动到“显式接口实现”
    • 哦,它就在那里,就在“显式接口实现”下的页面下方。这是为什么?当我有一个 FtpWebResponse 实例时,为什么这个方法没有出现在 IntelliSense 中?
    【解决方案2】:

    它确实具有通过继承的 Dispose 方法,但它是一个显式实现。要调用它,您必须使用

    ((IDisposable)myObject).Dispose();
    

    或者,当然,只需将其包装在 using 块中,因为它会为您进行显式调用。

    【讨论】:

    • +1 用于提及其明确实现。正如其他人所说,它在底座上,但你仍然会看到它 - 你回答了为什么你不能轻易看到它。
    • 使用显式实现的原因是什么?
    • @MCS,这是个好问题!实际上,对于为什么某些类具有显式 IDisposable 实现的 stackoverflow,这听起来像是一个很好的 问题,因为它有点掩盖了这样一个事实,即对象应该为没有查阅文档的普通开发人员处置每次他/她使用课程。
    【解决方案3】:

    当您显式实现interface 时,您将无法获得清单中的方法。您必须将该对象强制转换为已实现的 interface 才能访问该方法。

    public class MyClass : IDisposable
    {
        void IDisposable.Dispose()
        {
            throw new NotImplementedException();
        }
    }
    

    参考:http://msdn.microsoft.com/en-us/library/ms173157.aspx

    【讨论】:

      【解决方案4】:

      在基类WebResponse中实现

      void IDisposable.Dispose()
      {
      try
      {
          this.Close();
          this.OnDispose();
      }
      catch
      {
      }
      }
      

      alt text http://img227.imageshack.us/img227/2428/redgatesnetreflector.png

      【讨论】:

        【解决方案5】:

        它继承自实现这些方法的System.Net.WebResponse

        【讨论】:

          猜你喜欢
          • 2011-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-25
          • 1970-01-01
          • 1970-01-01
          • 2017-10-27
          • 2011-07-17
          相关资源
          最近更新 更多