Why would a class implement IDisposable explicitly instead of implicitly?

独自空忆成欢 提交于 2019-11-27 09:25:09
  • 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.

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().

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!