2013-02-28 194 views
2

因此,我在这里使用了一些代码,在这里我使用了一个字典来填充在自定义类中作为属性保存的两个不同字典。我这样做是为了提高效率。VBA:字典内存问题?填充字典,.removeall,填充问题

注意:通过对每个要设置的属性使用字典,我有解决此问题的解决方法,但这不是非常有效。

所以大致这里是我的代码:

for iKey = 1 to class.maxnumber ' 8 
    dTempDict.add iKey, cdbl(24) ' enforce to 24 for calcs later 
next iKey 

Set class.dict1 = dTempDict ' commit to class.dict1 

dTempDict.removeall 'wipe temp dictionary 

for iKey = 1 to class.maxnumber ' 8 
    dTempDict.add iKey, "word" ' something other than 24 to test 
next iKey 

Set class.dict2 = dTempDict 

所以上面的正常工作。然后我尝试循环并打印class.dict1的键,没有任何问题。然后,当我尝试将值分配给预先声明的dbl时,我陷入了困境。然后,我通过像这样每个键循环在不同的子类通过按地址:

dim dTempDict as scripting.dictionary 
Set dTempDict = class.dict1 
for each iKey in dTempDict 
msgbox typename(dTempDict.Item(iKey)) 
next iKey 

这带回来的结果......“字符串” ...混乱。然后我改变了我的值持有人到一个字符串,它的工作。我已经在类中检查了我的访问器,并且它们不会循环回错误的字典属性,因此即使我将它们分配给第二个,甚至执行.removeall,第二个字典的值也会填充到第一个字典中。

任何想法?

如上所述,对class.dict1和class.dict2使用不同的temp字典,它们被分配正确,但仍然令人困惑。

回答

0

当你做到这一点...

Set class.dict1 = dTempDict 
dTempDict.removeall 
'... 
Set class.dict2 = dTempDict 

...那么这两个dict1dict2指向同一个Dictionary对象(dTempDict)。

将一个对象变量赋值给另一个不会创建该对象的副本,而只会产生一个指向同一对象的额外“指针”。

您应该创建一个新的字典,而不是重复使用同一个字典分配给dict2

0

一般来说,我不喜欢在课堂上有字典,除了举办其他课程。我不知道你的情况,所以我不能对此发表评论。但无论“24”是什么,你都可以认为它应该是它自己的对象,你的班级将包含另一个集合班。顺便说一下,为此我使用集合而不是字典。然后,您可以访问之类的东西

clsDepartment.Employees.Count 

,而不是

clsDepartment.mydict(1) 

无论如何,你有什么,你应该填充在类字典而不是创建临时字典。如果您的类看起来像这样

Private mdcTwentyFour As Scripting.Dictionary 
Private mdcNotTwentyFour As Scripting.Dictionary 

Public Property Get TwentyFour() As Scripting.Dictionary 
    Set TwentyFour = mdcTwentyFour 
End Property 

Public Property Get NotTwentyFour() As Scripting.Dictionary 
    Set NotTwentyFour = mdcNotTwentyFour 
End Property 

Public Property Get MaxNumber() As Long 
    MaxNumber = 8 
End Property 

Private Sub Class_Initialize() 

    Set mdcTwentyFour = New Scripting.Dictionary 
    Set mdcNotTwentyFour = New Scripting.Dictionary 

End Sub 

然后你的个子看起来像这样

Sub FillClassDicts() 

    Dim clsClass As CClass 
    Dim i As Long 

    Set clsClass = New CClass 

    For i = 1 To clsClass.MaxNumber 
     clsClass.TwentyFour.Add i, 24 
     clsClass.NotTwentyFour.Add i, "word" 
    Next i 

    Debug.Print clsClass.TwentyFour.Count, clsClass.NotTwentyFour.Count 
    Debug.Print TypeName(clsClass.TwentyFour(1)), TypeName(clsClass.NotTwentyFour(5)) 

End Sub