【问题标题】:vba (catia) destroying objects from arrayvba(catia)从数组中销毁对象
【发布时间】:2013-09-18 07:18:32
【问题描述】:

我有一个关于通过数组从标准和自定义类中销毁对象的问题,这里是示例:

dim class1 As cClass1
dim class2 As cClass2
dim class3 As cClass3
....

Set class1 = New cClass1
Set class2 = New cClass2
Set class3 = New cClass3
....

使用它们后,我想在最后销毁它们以从内存中释放它们,但我想避免使用

Set class1 = Nothing 
Set class2 = Nothing 
.... 'and so on

我想用以下方式摧毁它们:

CRLS Array(class1, class2, class3, "and so on")

这里有一个 sub 可能会这样做:

Private Sub CLRS(ByRef arr As Variant)
    Dim i As Integer
    For i = 0 To UBound(arr)
        If Not arr(i) Is Nothing Then
            Set arr(i) = Nothing
            Debug.Print "Deleted" 'it will throw "Deleted" but it will not delete element itself
        Else
            Debug.Print "not deleted" 'just to see status of element
        End If
    Next
    Erase arr
End Sub

但不幸的是,如果我检查“销毁”元素是否真的免费,答案不是,只有选定元素的副本被设置为空。对象像 ByVal 一样传递给数组。

【问题讨论】:

  • 为什么?它们会在超出范围时被释放,在大多数情况下您不需要手动释放它们

标签: arrays vba destroy catia


【解决方案1】:

VBA 使用引用计数器销毁对象。当对象引用计数为零时,对象被销毁。假设您的 class1 变量通过将其设置为将计数器加一:

Set class1 = New cClass1

然后将对象传递给数组。

Array(class1, class2, class3, "and so on")

对象引用计数变为 2,因为现在数组有自己的引用。然后将数组引用设置为空,计数为 1,因为 class1 仍然具有引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2021-02-02
    • 2017-01-11
    • 2013-03-21
    相关资源
    最近更新 更多