请考虑以下代码:
Sub NestedCollections()
Dim col1 As Collection
Dim col2 As Collection
Dim col3 As Collection
Set col1 = New Collection
Set col2 = New Collection
Set col3 = New Collection
col2.Add "a"
col2.Add "b"
col2.Add "c"
col3.Add "d"
col3.Add "e"
col3.Add "f"
col1.Add col2
col1.Add col3
col1.Item(2).Add col3
Set col1 = Nothing
Set col2 = Nothing
Set col3 = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)
如果将监视添加到"col1",并展开"item(2)",您会注意到"item(4)"继续扩展.为什么会这样?
干杯,马雷克
一切正常,直到col1.Item(2).Add col3执行.
除此之外,col1.Item(2)就是col3按照这个指令:
col1.Add col3
Run Code Online (Sandbox Code Playgroud)
通过添加col3到col1.Item(2),您要添加一个指针col3来...... col3,这就是为什么"不断扩大" -第4项col3是col3自己:
col3.Add "d" 'col1.Item(2)(1)
col3.Add "e" 'col1.Item(2)(2)
col3.Add "f" 'col1.Item(2)(3)
col3.Add col3 'col1.Item(2)(4)
Run Code Online (Sandbox Code Playgroud)
我不建议使用这样的递归数据结构(即向其自身添加集合).