C#object.Dispose()或对象= NULL [英] c# object.Dispose() or object = null
问题描述
Hi我有一个对象是Disposable,我想知道什么是更好:
Hi I have an object has is Disposable and I would like to know what is better:
this.object.Dispose();
或
this.object = null;
或
this.object.Dispose();
this.object = null;
推荐答案
处置
更好,更好的方法是使用 中的对象,使用
块并让框架处理它。
Dispose
is better, even more better approach would be to use the object inside the using
block and let the framework dispose it.
For: this.object.Dispose();
vs this.object = null ;
将对象设置为 null
可能会导致丢弃不受管理的资源未处置。具有 IDisposable
的整个目标是确保在使用后未管理的资源处理。
Setting the object to null
may result in leaving out un-managed resources un-disposed. The whole object of having IDisposable
is to make sure that un-managed resources are disposed after their usage.
See: IDisposable - MSDN
此接口的主要用途是释放非托管资源。
当不再使用该对象时,垃圾回收器自动释放分配给
被管对象的内存。然而,不是
可能预测何时将发生垃圾收集。此外,
垃圾收集器不知道非托管资源,例如
窗口句柄或打开的文件和流。
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.
这篇关于C#object.Dispose()或对象= NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!