Why would a class implement IDisposable explicitly instead of implicitly?

后端 未结 4 2085
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 23:57

I was using the FtpWebResponse class and didn\'t see a Dispose method. It turns out that the class implements IDisposable, but does so explicitly so that you must first cas

相关标签:
4条回答
  • 2020-12-02 00:07

    This is normally done if the class has a Close method that is the exact same as Dispose. The original Dispose is hidden in an explicit implementation so that the exact same method doesn't have two names.

    It's officially recommended here:

    Do implement a Close method for cleanup purposes if such terminology is standard, for example as with a file or socket. When doing so, it is recommended that you make the Close implementation identical to Dispose...

    Consider implementing interface members explicitly to hide a member and add an equivalent member with a better name.

    Occasionally a domain-specific name is more appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In this case, implement Dispose privately and create a public Close method that calls Dispose.

    (P.S. I disagree with this convention.)

    0 讨论(0)
  • 2020-12-02 00:09

    In addition to what's been said, I might suggest that implementing IDisposable explicitly encourages use of the using block, as it can be used on any type which implements IDisposable and it is more natural (to most people, anyway) to write this:

    using (var response = GetResponse())
    {
        // do something
    }
    

    Than this:

    var response = GetResponse();
    
    // do something
    
    ((IDisposable)response).Dispose();
    

    I'm not sure that would be a developer's intention in explicitly implementing IDisposable, but it's possible.

    0 讨论(0)
  • 2020-12-02 00:13

    It's a little weird looking to me too. For what it's worth: the base class (WebResponse) implements a Close() method. Reflector shows that WebResponse's Dispose() method just calls Close() and an Internal OnDispose virtual that does nothing.

    I have to confess that it smells a little to me, but I bet that they explicitly implemented IDisposable so that there would not be confusion in Intellisense between calling Close() or Dispose().

    0 讨论(0)
  • 2020-12-02 00:14
    • Occasionally a class will have a Dispose method that is part of the interface but doesn't actually need to be called because the only resource to dispose of is memory: MemoryStream, for example.
    • As mentioned by others, if the class has a Close method that does the same thing as Dispose, arguably Dispose only needs to exist to support the "using" pattern so it may as well be explicit.
    0 讨论(0)
提交回复
热议问题