我的Main Sub中有一个字典(KEY = string; VALUE = Class Object)。类对象由两个字典组成。当我收集数据并检查存储在字典值(类对象 - 字典)中的值时,我注意到只存储了最后一个值。我的意思是我的Main Sub中我的字典中的所有值都指向相同的字典引用,因此,我的类对象的所有实例都包含相同的数据。这意味着我需要复制我的类对象(深层复制?)。我之前已成功完成此操作,而Class Objects只存储了简单的值,但没有存储字典。我需要帮助克隆包含字典的类对象。
MAIN SUB
Dim dGroup As New Scripting.Dictionary ' Main Dictionary
'
' loop thru a listbox
For i = 0 To UserForm1.ListBox1.ListCount - 1
Gname = UserForm1.ListBox1.List(i) ' get listbox names
' populate temp dictionary
Set dic = FNC.GET_SESSION_FILE_ELEMENTS(mySesFile, Gname)
'
' instantiate new Class Object
Dim NewCol As New cVM_Col
Call NewCol.INIT(dic) ' pass the dictionary to a 'constructor'
dGroup.Add Gname, NewCol.CLONE ' add to the MAIN SUB dictionary
'
Set dic = Nothing ' clear the temp dictionary
Next i
CLASS OBJECT
Private dElms As Scripting.Dictionary
Private dDat As Scripting.Dictionary
'
Private Sub Class_Initialize()
Set dElms = New Scripting.Dictionary
Set dDat = New Scripting.Dictionary
End Sub
'
Public Sub INIT(inp As Scripting.Dictionary)
Set dElms = inp
End Sub
'
Public Function CLONE()
Set CLONE = New cVM_Col
Set CLONE.dElms = dElms ' <-- THIS IS WHERE IT CRASHES
Set CLONE.dDat = dDat
End Function
通常我的CLONE函数在我只克隆简单数据类型(如String或Long或Double)时有效。我从来没有用字典做过这个。
答案 0 :(得分:1)
要CLONE我的CLASS对象中的字典对象,我必须进行以下更改:
CLASS OBJECT (修改CLONE功能)
Public Function CLONE()
Set CLONE = New cVM_Col
CLONE.Elms = dElms
CLONE.Dat = dDat
End Function
(已添加属性)
Public Property Get Elms() As Scripting.Dictionary
Set Elms = dElms
End Property
Public Property Let Elms(p As Scripting.Dictionary)
Set dElms = p
End Property
'
Public Property Get Dat() As Scripting.Dictionary
Set Dat = dDat
End Property
Public Property Let Dat(p As Scripting.Dictionary)
Set dDat = p
End Property