当所有成员都被明确处置时,类是否需要实现IDisposable? [英] Does a class need to implement IDisposable when all members are explicitly disposed?
问题描述
试图了解何时需要实施IDisposable:
Trying to understand when implementation of IDisposable is necessary:
我写了一个小例子。
public class FileManager
{
private FileStream fileStream;
public void OpenFile(string path)
{
this.fileStream = File.Open(path, FileMode.Open, FileAccess.Read);
}
public void CloseFile(string path)
{
if ( this.fileStream != null && this.fileStream.CanRead)
{
this.fileStream.Close();
}
this.fileStream.Dispose();
}
}
// client
var manager = new FileManager();
manager.Open("path");
manager.Close("path");
此类是否需要实现IDisposable,因为它具有托管资源(FileStream),该资源可保存在非托管资源中资源(文件)?还是我不必在类中清理IDisposable?
Does this class need to implement IDisposable because it has a managed resource (FileStream) which holds onto an unmanaged resource (a file)? Or do I not have to implement IDisposable because I am cleaning up within the class?
困惑。
推荐答案
对于实现 IDisposable
且可能以非平凡的方式实现的任何类型的每个实例,必须在每时每刻能够确定该实例将如何处置
d。在大多数情况下,这意味着每个 IDisposable
实例将具有定义明确的所有者,该所有者负责调用 Dispose
。在类创建的 FileStream
实例的情况下,您的类是所有者,因为其他任何东西都无法 Dispose $ c $
For every instance of any type which implements IDisposable
and might do so in a non-trivial fashion, it must at every moment be possible to identify how that instance will be Dispose
d. In most cases, this means that each IDisposable
instance will have a well-defined owner, which is responsible for calling Dispose
. In the case of the FileStream
instance created by the class, your class is the owner, since nothing else will be able to Dispose
it.
具有引用其拥有的 IDisposable
实例的字段的类应该几乎总是实现 IDisposable
,并使用其 Dispose
方法来 Dispose
他们拥有的 IDisposable
对象。您的班级有这样一个领域;因此,它应该实现 IDisposable
。
Classes with fields that references to IDisposable
instances which they own should almost always implement IDisposable
, and use their Dispose
method to Dispose
the IDisposable
objects they own. Your class has such a field; it should thus implement IDisposable
.
只要有可能,就应该设计一个需要清除的类,以便调用 IDisposable.Dispose
就可以执行所需的所有清理工作。在某些情况下,不使用其他方法执行清理可能是不切实际的,但是这些情况很少见。如果可以设计一个类,使 Dispose
负责所有必要的清理工作,则应该这样做。
Whenever possible, a class which requires cleanup should be designed so that calling IDisposable.Dispose
on it will suffice to perform any and all such cleanup as may be needed. In some cases, it may be impractical to perform cleanup without using some other method, but those cases are pretty rare. If one can design a class so that Dispose
will take care of all necessary cleanup, one should do so.
这篇关于当所有成员都被明确处置时,类是否需要实现IDisposable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!