是否需要将 Objects 设置为 Nothing [英] Is there a need to set Objects to Nothing

查看:38
本文介绍了是否需要将 Objects 设置为 Nothing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是读到,一旦我完成了对象,建议将它们设置为空.但我通常只在表单内的函数中使用它们.

I always read that it is recommended to set objects to nothing, once I am done with them. But I normally use them only in functions inside forms.

离开函数作用域的时候,是不是引用丢失,内存释放,不管对象设置为Nothing?

Isn't the reference lost and memory released when the function scope is left, regardless of setting objects to Nothing?

即真的有必要这样做吗:

i.e. is it really necessary to do:

Set db = Nothing
Set record_set = Nothing

推荐答案

VB 使用所谓的引用计数"垃圾收集器.

VB uses a so-called "reference counting" garbage collector.

基本上,当一个变量超出范围时,被引用对象的引用计数器就会递减.当您将对象引用分配给另一个变量时,引用计数器会增加.

Basically, the moment a variable goes out of scope, the reference counter on the referenced object is decremented. When you assign the object reference to another variable, the reference counter is incremented.

当计数器达到零时,对象准备好进行垃圾回收.一旦发生这种情况,对象资源将被释放.函数局部变量很可能会引用一个引用计数永远不会大于 1 的对象,因此在函数结束时对象资源将被释放.

When the counter reaches zero, the object is ready for garbage collection. The object resources will be released as soon as this happens. A function local variable will most likely reference an object whose reference count never goes higher than 1, so object resources will be released when the function ends.

将变量设置为 Nothing 是显式减少引用计数器的方法.

Setting a variable to Nothing is the way to decrease the the reference counter explicitly.

例如,您读入一个文件,并在 ReadAll() 调用后立即将文件对象变量设置为 Nothing.文件句柄将立即释放,您可以花时间处理其内容.

For example, you read in a file, and set the file object variable to Nothing right after the ReadAll() call. The file handle will be released immediately, you can take your time process its contents.

如果您没有设置为 Nothing,文件句柄的打开时间可能超过绝对必要的时间.

If you don't set to Nothing, the file handle might be open longer than absolutely necessary.

如果您不是处于必须解除对宝贵资源的阻塞"类型的情况,那么简单地让变量超出范围就可以了.

If you are not in a "must unblock valuable resource" kind of situation, simply letting the variables go out of scope is okay.

这篇关于是否需要将 Objects 设置为 Nothing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆