如何迭代字典?
How to iterate dictionary?
我正在尝试遍历字典但遇到错误 "Object required"。相关代码如下。
首先,我创建了一个字典。
Dim customers
Set customers = CreateObject("Scripting.Dictionary")
我也定义了"cCustomer"的class,然后像这样使用字典。
Set customer = New cCustomer
customer.Init location, first, last
customers.Add location, customer
然后我用"For Each"来迭代
Dim cc
For Each cc in customers.items
...
Next
没关系。但是我真的很想声明 "cc" with type.
Dim cc As cCustomer
但如果我这样做,VB 运行时会在 "For Each" 行抱怨 "Object required"。我认为这与创建字典时缺少类型声明有某种关系?我对 VB 还是个新手。感谢您的帮助。
更多:为什么这不是重复的...
我已经尝试了 link 建议的解决方案,即 (a) 使用字典而不是 "Scripting.Dictionary",以及 (b) "Dim cc As Variant"。它像以前一样工作,但是如果我将 "cc" 提供给一个参数具有特定类型的函数,它仍然会失败。
Public Function foo(customer As cCustomer) As String
...
End Function
Dim cc As Variant
For Each cc in customers.items
foo(cc)
Next
错误是"ByRef argument type mismatch"。
这就是我真正需要将 "cc" 声明为 "cCustomer" 的原因,但它有 "Object required".
的错误
Dim cc As cCustomer
For Each cc In customers.items
...
根据评论
- 已尝试 "Dim cc As Object",但无效 ("Object required")。
- 试过 "remove Dim cc",也不行 ("ByRef argument type mismatch")。
我可以在函数定义中做 "ByVal" 或使用另一个变量,但这会涉及额外的副本。类型转换之类的东西可能会有所帮助...
有点麻烦,可能有更好的方法,但是这个怎么样:
dim loc as variant
dim cc as cCustomer
for each loc in Customers
set cc = Customers(loc)
foo(cc)
next loc
甚至可以做到 foo (Customers(loc))
,但我怀疑您会再次遇到类型不匹配错误。我认为您不能使用 byval
传递对象
我正在尝试遍历字典但遇到错误 "Object required"。相关代码如下。
首先,我创建了一个字典。
Dim customers
Set customers = CreateObject("Scripting.Dictionary")
我也定义了"cCustomer"的class,然后像这样使用字典。
Set customer = New cCustomer
customer.Init location, first, last
customers.Add location, customer
然后我用"For Each"来迭代
Dim cc
For Each cc in customers.items
...
Next
没关系。但是我真的很想声明 "cc" with type.
Dim cc As cCustomer
但如果我这样做,VB 运行时会在 "For Each" 行抱怨 "Object required"。我认为这与创建字典时缺少类型声明有某种关系?我对 VB 还是个新手。感谢您的帮助。
更多:为什么这不是重复的...
我已经尝试了 link 建议的解决方案,即 (a) 使用字典而不是 "Scripting.Dictionary",以及 (b) "Dim cc As Variant"。它像以前一样工作,但是如果我将 "cc" 提供给一个参数具有特定类型的函数,它仍然会失败。
Public Function foo(customer As cCustomer) As String
...
End Function
Dim cc As Variant
For Each cc in customers.items
foo(cc)
Next
错误是"ByRef argument type mismatch"。
这就是我真正需要将 "cc" 声明为 "cCustomer" 的原因,但它有 "Object required".
的错误Dim cc As cCustomer
For Each cc In customers.items
...
根据评论
- 已尝试 "Dim cc As Object",但无效 ("Object required")。
- 试过 "remove Dim cc",也不行 ("ByRef argument type mismatch")。
我可以在函数定义中做 "ByVal" 或使用另一个变量,但这会涉及额外的副本。类型转换之类的东西可能会有所帮助...
有点麻烦,可能有更好的方法,但是这个怎么样:
dim loc as variant
dim cc as cCustomer
for each loc in Customers
set cc = Customers(loc)
foo(cc)
next loc
甚至可以做到 foo (Customers(loc))
,但我怀疑您会再次遇到类型不匹配错误。我认为您不能使用 byval