Syntax 使用RemoveAll()发布嵌套脚本.Dictionary

Syntax 使用RemoveAll()发布嵌套脚本.Dictionary,syntax,dictionary,vb6,removeall,Syntax,Dictionary,Vb6,Removeall,我在这里找到的主题回答了我所寻找的一半: 在我的例子中,值是字典的实例,所以我有字典对象的嵌套层次结构 我的问题是我是否需要调用每个子字典的RemoveAll ' just for illustration Dim d As Dictionary Set d = New Dictionary Set d("a") = New Dictionary Set d("b") = New Dictionary ' Are the next section of code necessary? '

我在这里找到的主题回答了我所寻找的一半:

在我的例子中,值是字典的实例,所以我有字典对象的嵌套层次结构

我的问题是我是否需要调用每个子字典的RemoveAll

' just for illustration
Dim d As Dictionary
Set d = New Dictionary

Set d("a") = New Dictionary
Set d("b") = New Dictionary

' Are the next section of code necessary?
' -------------------- section start
Dim key As Variant
For Each key In d
    d.Item(key).RemoveAll
Next
' -------------------- section end

d.RemoveAll
Set d = Nothing
考虑一下这个代码

Option Explicit

Private m_cCache As Collection

Private Sub Form_Load()
    ' just for illustration
    Dim d As Dictionary
    Set d = New Dictionary

    Set d("a") = New Dictionary
    Set d("b") = New Dictionary

    d("b").Add "c", 123
    SomeMethod d

    ' Are the next section of code necessary?
    ' -------------------- section start
    Dim key As Variant
    For Each key In d
        d.Item(key).RemoveAll
    Next
    ' -------------------- section end

    d.RemoveAll             '--- d("b") survives
    Set d = Nothing         '--- d survives

    Debug.Print "main="; m_cCache("main").Count, "child="; m_cCache("child").Count
End Sub

Private Sub SomeMethod(d As Dictionary)
    Set m_cCache = New Collection

    m_cCache.Add d, "main"
    m_cCache.Add d("b"), "child"
End Sub

如果没有清理,d部分(“b”)实际上不会被触及——既不会删除子项,也不会终止实例。

好的,我想我可以通过下一个测试来回答自己

Sub Main()
  Dim d As Dictionary
  Dim i, j As Integer
  Dim sDummy As String * 10000
  For i = 1 To 1000
    Set d = New Dictionary      ' root dict.
    Set d("a") = New Dictionary ' child dict.
    For j = 1 To 1000
      d("a").Add j, sDummy
    Next j
    'd("a").RemoveAll
    d.RemoveAll
    Set d = Nothing
  Next i
End Sub

我注释掉了
d(“a”)。删除了所有的
(我的孩子字典),并且没有任何内存泄漏。这意味着在根(
d
)上调用
RemoveAll
就足够了,这就是我所需要知道的。

在VB6中,所有对象(通过COM)都要进行引用计数,因此,除非有一个循环,否则不需要手动处理。

什么是必要的?你想实现什么?我想释放所有对象,正如我所读到的(在上面的主题中),RemoveAll将内部的所有对象设置为Nothing,非常好,但不确定该函数是否为递归函数。感谢您的响应。你在这里讲的是关于清理多重引用的,我知道的,嗯。。。在我的例子中,没有对任何Dictionary对象的额外引用,但是从这一点来看,也许你试图让我得出一个结论,我应该在d.RemoveAll之前调用d(“a”)和d(“b”),也就是说,我需要包含我的代码部分?这取决于你在
Dictionary
s中存储的引用类型。如果您有类似于
d(“a”)。添加“main”,d
这会带来一个循环引用,如果没有
RemoveAll
调用,就无法发布该引用。如果您的清理部分是一个通用函数,那么最好明确使用
RemoveAll
,并以性能换取安全。我看不出您为什么需要在根级别字典上调用
RemoveAll
。释放对它的最后一个引用本身应该可以做到这一点。顺便说一句,我没有在代码中修复它,但是在VB6中
Dim I,j As Integer
意味着
Dim I As Object,j As Integer
@MarkHurd-感谢您提供的关于
Dim I,j As Integer
的提示。由于我不熟悉VB6,我认为这两个变量都是整数。再次感谢!