gpt4 book ai didi

VBA字典继承无链接

转载 作者:行者123 更新时间:2023-12-01 16:05:13 24 4
gpt4 key购买 nike

我想让一个字典继承另一个字典的键和值。之后,如果我修改一本字典,它不会修改另一本字典。我认为这很简单:

Sub testdic()
Dim d
Set d = CreateObject("Scripting.Dictionary")
d.Add "first", 1
Dim s
Set s = d
s.Add "second", 2
End Sub

上面的代码将键“second”和值 2 添加到 s 和 d 字典中,而我希望它仅添加到 s 字典中。是否可以在不创建类的情况下执行此操作?

最佳答案

这是一个更通用的解决方案,它不限制您使用的键或值。该函数执行字典的“浅复制”。它返回一个新的字典对象,但原始字典中的任何对象本质上都是通过引用传递到新字典中的。

如果原始字典中的项目不是对象(字符串、整数等),则这是一个没有实际意义的问题。但是,如果这些项目是对象,那么对字典之间浅复制的任何对象的更改都会更改“两个”位置的对象(我将“两个”放在引号中,因为实际上只有一个对象,只有多个引用指向它)。

Function DictionaryShallowCopy(Dict As Object) As Object           ' <-- Late-bound
'Function DictionaryShallowCopy(Dict As Dictionary) As Dictionary ' <-- Early-bound
If Dict Is Nothing Then Exit Function

Set DictionaryShallowCopy = CreateObject("Scripting.Dictionary") ' <-- Late-bound
'Set DictionaryShallowCopy = New Dictionary ' <-- Early-bound
If Dict.Count = 0 Then Exit Function

Dim Key As Variant
For Each Key In Dict.Keys
DictionaryShallowCopy.Add Key, Dict.Item(Key)
Next Key

End Function

上述函数使用后期绑定(bind),因此您不需要对脚本运行时的引用。这使您可以轻松地将此函数放入任何 VBA 项目中,而不会出现任何问题。早期绑定(bind)将为您带来性能提升和智能感知,因此如果可能的话使用它是有意义的。

下面是一个示例过程,说明了上述函数的作用(请注意,该示例需要对 Microsoft 脚本运行时的引用)。如果您有任何疑问,请在评论中提问。

Sub Sample_DictionaryShallowCopy()
Dim A As Dictionary, A_Nothing As Dictionary
Set A_Nothing = DictionaryDeepCopy(A)
Debug.Print A_Nothing Is Nothing
'True

Set A = New Dictionary

Dim A0 As Dictionary
Set A0 = DictionaryDeepCopy(A)

A.Add "Texas", "Austin"
A.Add "New York", "Albany"

Dim B As Dictionary
Set B = DictionaryShallowCopy(A)
B.Add "Pennsylvania", "Harrisburg"

Debug.Print A0.Count, A.Count, B.Count
' 0 2 3

Dim C As New Dictionary
C.Add A, "Dictionary A"
C.Add B, "Dictionary B"
Dim D As Dictionary
Set D = DictionaryShallowCopy(C)
'The Key type is maintained during the copy, even if the key is an object:
Debug.Print TypeName(C.Keys(0)), TypeName(D.Keys(0))
'Dictionary Dictionary

Dim E As New Dictionary
E.Add "DictA", A

Dim F As Dictionary
Set F = DictionaryShallowCopy(E)
F.Add "DictB", B

F("DictA")("Texas") = "Houston"
'This is a shallow copy, so the items that are objects are
' "copied" by reference, not by value:
Debug.Print A("Texas"), E("DictA")("Texas"), F("DictA")("Texas")
'Houston Houston Houston

'If this were a DeepCopy, then the above line would have outputted:
'Austin Austin Houston
End Sub

关于VBA字典继承无链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com