Explicit implementation of IDisposable

人走茶凉 提交于 2019-12-03 05:26:32

I'd say it's unusual to have an explicit implementation of IDisposable.Dispose unless you have an alternate equivalent method (e.g. Close).

In which case your wrapper class could call Close rather than casting.

An example is the WebResponse class in the Framework <= V3.5. Interestingly there is a public Dispose method in .NET 4, so maybe Microsoft has now decided that an explicit implementation may not be good practice.

Shawn Farkas, a design engineer on the CLR security team writes in MSDN magazine that

Although the using block will work with classes that do have an explicit IDisposable implementation, I recommend that classes never implement the interface this way. If you explicitly implement IDisposable, developers who are exploring your object model using IntelliSense® in Visual Studio® will not notice that the object has a Dispose method

I would say it's good practice, it forces (unless you want to cast to IDisposable!!) the use of using

using (ClassWithIDisposable) {
}

Dispose will be called even in the event of an exception

Also when using IOC frameworks like castle and unity you end up having to inherit IDisposable to your interface so it can be called. These frameworks allow for AOP whereby you don't have a reference to your solid class only an interface......

IMHO, there's only one proper reason for a class to implement IDisposable explicitly, which would be if it's expected that nobody would actually have to call it. The fact that a class implements IDisposable explicitly could be seen as an indicator that one may safely create an object of that particular class, though not necessarily an object of a derived class, and simply abandon it when one was done with it. The lack of a directly-available Dispose method on a particular class could then be seen as an indicator that calling Dispose on an object known to be of that particular class would not be needed.

Note that having and using a reference to an object which implements IDisposable, without realizing that it does, is not a problem; acquiring ownership of such an object, however, is. A factory method whose return type does nothing with IDisposable.Dispose and implements it explicitly, but which sometimes returns an object that expects proper Disposal, would be a recipe for leaks. A class should not explicitly implement IDisposable if it might be used as the return type of such a factory method.

Personally, my inclination would be to Dispose all objects that implement IDisposable, whether they need it or not. Nonetheless, knowing that certain particular types of IDisposable object may be very useful in cases where ensuring proper disposal would otherwise be difficult or awkward.

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