首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用RemoveAll()释放嵌套的Scripting.Dictionary

使用RemoveAll()释放嵌套的Scripting.Dictionary
EN

Stack Overflow用户
提问于 2012-12-19 10:14:01
回答 3查看 562关注 0票数 2

我在这里找到了一个主题,它回答了我正在寻找的一半:Does Scripting.Dictionary's RemoveAll() method release all of its elements first?

在我的例子中,值是Dictionary的实例,所以我嵌套了Dictionary对象的层次结构。

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

代码语言:javascript
复制
' 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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-12-30 15:06:37

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

票数 0
EN

Stack Overflow用户

发布于 2012-12-19 18:17:37

请考虑下面的代码

代码语言:javascript
复制
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")实际上将保持不变--既不会删除子项,也不会终止实例。

票数 0
EN

Stack Overflow用户

发布于 2012-12-20 05:35:25

好了,我想我可以用我做的下一个测试来回答我自己。

代码语言:javascript
复制
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").RemoveAll (我的子字典),没有任何内存泄漏。这意味着在根(d)上调用RemoveAll就足够了,这就是我需要知道的全部内容。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13944597

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档