任何意义的处置设置OBJ =空(没有)()? [英] Any sense to set obj = null(Nothing) in Dispose()?
问题描述
有没有任何意义,自定义对象设置为空
在<$(没有
在VB.NET) C $ C>的Dispose()的方法? !
难道这防止内存泄漏,或者是无用的。
让我们考虑两个例子:
公共类Foo:IDisposable的
{
私人酒吧酒吧; //标定制.NET对象
公共美孚(酒吧吧){
this.bar =栏;
}
公共无效的Dispose(){
栏= NULL; //任何意义?
}
}
公共类Foo:RichTextBox的
{
//这可能是也:GDI +,TCP套接字,SQL连接,其他的重对象
私人位图背景图像;
公共美孚(位图背景图像){
this.backImage =背景图像;
}
保护覆盖无效的Dispose(BOOL处置){
如果(处置){
背景图像= NULL; //任何意义?
}
}
}
的Dispose()
是允许清理不是由垃圾收集处理的资源。对象由GC的照顾,所以真的没有必要在正常情况下设置参考为null。
唯一的例外是,如果你希望主叫方拨打的Dispose
的和的扶住后该实例。在这种情况下,也可以是设置内部参考为null一个好主意。然而,一次性实例典型地设置,并在同一时间释放。在这种情况下,它不会带来很大的区别。
Is there any sense to set custom object to null
(Nothing
in VB.NET) in the Dispose()
method?
Could this prevent memory leaks or it's useless?!
Let's consider two examples:
public class Foo : IDisposable
{
private Bar bar; // standard custom .NET object
public Foo(Bar bar) {
this.bar = bar;
}
public void Dispose() {
bar = null; // any sense?
}
}
public class Foo : RichTextBox
{
// this could be also: GDI+, TCP socket, SQl Connection, other "heavy" object
private Bitmap backImage;
public Foo(Bitmap backImage) {
this.backImage = backImage;
}
protected override void Dispose(bool disposing) {
if (disposing) {
backImage = null; // any sense?
}
}
}
The purpose of Dispose()
is to allow clean up of resources that are not handled by the garbage collector. Objects are taken care of by GC, so there's really no need to set the reference to null under normal circumstances.
The exception is if you expect the caller to call Dispose
and hold on to the instance after that. In that case, it can be a good idea to set the internal reference to null. However, disposable instances are typically disposed and released at the same time. In these cases it will not make a big difference.
这篇关于任何意义的处置设置OBJ =空(没有)()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!