所以我在这里使用了一段代码,其中我使用一个字典来填充作为自定义类中的属性的两个不同的字典。我这样做是为了效率。
注意:对于这个问题,我有一个变通的解决方案,即为我想要设置的每个属性使用字典,但这不是非常有效。
我的代码大致如下: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的键。没问题。然后,当我试图将这些值分配给预先声明的dbl时,我遇到了麻烦。然后在不同的子传递类byref:
中循环遍历每个键,就像这样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。dic2,它们被分配正确,但这仍然令人困惑。
当你这样做的时候…
Set class.dict1 = dTempDict
dTempDict.removeall
'...
Set class.dict2 = dTempDict
…那么dict1
和dict2
都指向同一个Dictionary对象(dTempDict
)。
将一个对象变量赋值给另一个对象变量并不会创建该对象的副本,而只是产生一个指向同一对象的额外"指针"。
您应该创建一个新的Dictionary,而不是重新使用相同的Dictionary来分配给dict2
。
一般来说,我不喜欢在课堂上使用字典,除非用来容纳其他类。我不了解你的情况,所以我不能评论。但是无论'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可能看起来像这样
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