简体   繁体   English

为什么Stream类要实现IDisposable?

[英]Why does the Stream class implement IDisposable?

Why does the Stream class implement IDisposable?为什么Stream类要实现IDisposable? I think the Stream class itself doesn't have any unmanaged resources.我认为 Stream 类本身没有任何非托管资源。 Certainly, some of the subclasses have unmanaged resources (eg FileStream), but not all of subclasses have unmanaged resources (eg MemoryStream).当然,某些子类具有非托管资源(例如 FileStream),但并非所有子类都具有非托管资源(例如 MemoryStream)。

If the answer to the above question is "because the subclasses of the Stream class may have unmanaged resources", then why doesn't the Object class implement IDisposable?如果上述问题的答案是“因为Stream类的子类可能有非托管资源”,那为什么Object类没有实现IDisposable呢?

No one said the resources had to be unmanaged.没有人说资源必须不受管理。 It has resources that need to be cleaned up.它有需要清理的资源。 You can accomplish the same thing with Close() , but the idea is that you can use it with a using statement, and then the resources will be guaranteed to be cleaned up, even in the case of an exception.你可以用Close()完成同样的事情,但想法是你可以用using语句来使用它,然后保证资源被清理,即使在出现异常的情况下也是如此。

using (var s = new System.IO.MemoryStream())
{
    //do something.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM