VBA中Set语句与直接赋值的区别——基于VBA-JSON源码分析
VBA中Set赋值与直接赋值的差异疑问
最近我在研究VBA-JSON的源码,其中负责解析以{开头的JSON对象到内存的json_ParseObject函数代码如下:
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Dictionary Dim json_Key As String Dim json_NextChar As String Set json_ParseObject = New Dictionary json_SkipSpaces json_String, json_Index If VBA.Mid$(json_String, json_Index, 1) <> "{" Then Err.Raise 10001, "JSONConverter", json_ParseErrorMessage(json_String, json_Index, "Expecting '{'") Else json_Index = json_Index + 1 Do json_SkipSpaces json_String, json_Index If VBA.Mid$(json_String, json_Index, 1) = "}" Then json_Index = json_Index + 1 Exit Function ElseIf VBA.Mid$(json_String, json_Index, 1) = "," Then json_Index = json_Index + 1 json_SkipSpaces json_String, json_Index End If json_Key = json_ParseKey(json_String, json_Index) json_NextChar = json_Peek(json_String, json_Index) If json_NextChar = "[" Or json_NextChar = "{" Then Set json_ParseObject.Item(json_Key) = json_ParseValue(json_String, json_Index) Else json_ParseObject.Item(json_Key) = json_ParseValue(json_String, json_Index) End If Loop End If End Function
我注意到代码里根据下一个字符是[或{,用了两种不同的赋值方式,想请教这两行代码的区别:
第一种写法:
Set json_ParseObject.Item(json_Key) = json_ParseValue(json_String, json_Index)
第二种写法:
json_ParseObject.Item(json_Key) = json_ParseValue(json_String, json_Index)
我查阅了相关资料,知道当解析器遇到{或[时,json_ParseValue会返回Dictionary或Collection这类对象;遇到布尔值、字符串、整数等则返回值类型。但我还是没完全搞懂:是不是Set是复制返回对象的地址,直接赋值则是复制对象本身?是不是因为前者后续可能需要修改返回的对象,所以要按地址传递(类似C++里的&)?
内容的提问来源于stack exchange,提问作者Nicholas Humphrey
相关产品推荐
相关产品推荐

