Why would a class implement IDisposable explicitly instead of implicitly?

后端 未结 4 2108
伪装坚强ぢ
伪装坚强ぢ 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: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.

提交回复
热议问题