什么是IDisposable的呢? [英] What is IDisposable for?
问题描述
如果.NET有垃圾回收,那么为什么你一定要明确地调用的IDisposable
?
If .NET has garbage collection then why do you have to explicitly call IDisposable
?
推荐答案
垃圾收集是内存。您需要处置非内存资源 - 文件句柄,插座,GDI +处理,数据库连接等等。这是典型的什么下部的一个的IDisposable
键入,尽管实际的手柄可以说是相当很长的路要走下来引用链。例如,您可能会处置
的的XmlWriter
其中配置一台的StreamWriter
它有一个参考,它部署在的FileStream
的是的有一个参考,它释放的文件句柄本身。
Garbage collection is for memory. You need to dispose of non-memory resources - file handles, sockets, GDI+ handles, database connections etc. That's typically what underlies an IDisposable
type, although the actual handle can be quite a long way down a chain of references. For example, you might Dispose
an XmlWriter
which disposes a StreamWriter
it has a reference to, which disposes the FileStream
it has a reference to, which releases the file handle itself.
这篇关于什么是IDisposable的呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!