如何破坏物体 [英] How to destroy an object

查看:117
本文介绍了如何破坏物体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中,似乎 Set Object = Nothing 并没有破坏 Fs 对象:

  Sub Test2()
Dim Fs作为新FileSystemObject
Set Fs = Nothing
MsgBox Fs.Drives .Count'这行有效
End Sub

最后一行没有错误!多数民众赞成表示 Fs 对象仍然存在,对吧?。



那么如何销毁这个 Fs 对象。

解决方案

确保对象正确销毁的另一种方法是产生对象引用 With 块(即不声明局部变量):

  Sub Test()
使用新的FileSystemObject
MsgBox .Drives.Count
结尾用
结尾Sub

对象仅存在于 With 块内,并且当执行到达 End With时令牌,如果您使用自定义类模块进行尝试,则会注意到该类的 Class_Terminate 处理程序正在运行,从而有效地确认了对



对于如新一样,



(注意:如果您有要检查的代码,请知道它可以运行在实际的VBE中,比在网站上更快



(如果尚不清楚,我会很努力参与Rubberduc k项目)


It seems that Set Object = Nothing didn't destroy the Fs Object in this code:

Sub Test2()
    Dim Fs As New FileSystemObject
    Set Fs = Nothing
    MsgBox Fs.Drives.Count ' this line works
End Sub

The last line works with no errors!. thats mean Fs Object is still exists, right?.

So how to destroy this Fs Object.

解决方案

Another way to ensure proper destruction of an object, is to yield its object reference to a With block (i.e. don't declare a local variable):

Sub Test()
    With New FileSystemObject
        MsgBox .Drives.Count
    End With
End Sub

The object only ever exists inside the With block, and when execution reaches the End With token, if you try it with a custom class module you'll notice that the the class' Class_Terminate handler runs, effectively confirming the proper destruction of the object.

As for the As New quirk, as was already explained, if you intend to set the object reference to Nothing inside that scope, don't declare it with As New, because VBA will set the object reference to Nothing, but will also happily ("helpfully") create a new instance for you as soon as you re-reference it again, be it only to verify that the object Is Nothing.

Side note, this (annoying) counter-intuitive behavior is specifically what's behind the reasoning for Rubberduck's Object variable is self-assigned code inspection:

(note: if you've got code you want to inspect, know that it runs much faster in the actual VBE than on the website)

(if it wasn't clear already: I'm heavily involved with the Rubberduck project)

这篇关于如何破坏物体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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