从字典返回类属性的数组 [英] Return array of class properties from dictionary
问题描述
背景:
虽然最近尝试回答一个问题,但我还是想着是否有可能返回一个数组类对象属性直接来自字典项.
While recently trying to answer a question, I had myself thinking if it would be possible to return an array of class object properties directly from a dictionary item.
代码:
将TstClass
想象为具有以下代码的类模块:
Imagine TstClass
as a class module with the following code:
Public val1 As Variant
Public val2 As Variant
Public val3 As Variant
然后这段代码进行测试:
Then this code to test:
Sub Test()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim lst As TstClass, key As Variant, arr As Variant
For x = 1 To 3
Set lst = New TstClass
lst.val1 = "A" & x
lst.val2 = "B" & x
lst.val3 = "C" & x
dict.Add x, lst
Next x
For Each key In dict
arr = Array(dict(key).val1, dict(key).val2, dict(key).val3)
Next key
End Sub
问题:
在上述情况下,Array(dict(key).val1, dict(key).val2, dict(key).val3)
将返回数组,但如果我们想象val4-val50
,它将变成更多代码.使用Array(...)
或将其逐行写出Debug.Print Dict(key).Valx
.
In the above case Array(dict(key).val1, dict(key).val2, dict(key).val3)
will return the array just fine, but if we imagine val4-val50
it will become a lot more code. Either with Array(...)
or writing it out line by line Debug.Print Dict(key).Valx
.
问题:
是否可以直接从字典键的类对象属性返回数组?对我来说,最明显的尝试是arr = Dict(key)
希望它能以某种方式识别出我需要该物品的所有属性.最重要的是,不允许将常量,数组,用户定义的类型声明为Public,因此Public Vals(0 to 2)
之类的方法也不起作用.
Is it possible to return an array directly from the class object properties from the dictionary key? The most obvious thing to try for me was arr = Dict(key)
hoping it would somehow recognize I needed all properties from the item. On top of that it's not allowed to declare Constants, Arrays, User Defined Types as Public, so something like Public Vals(0 to 2)
won't work either.
谢谢你, JvdV
推荐答案
不确定这是否是您想要的 ,但是可以在您的类中创建一个方法来构建一个所需属性的数组.然后,您可以在该类的每个实例上调用它以获取数组详细信息.
Not sure if this is exactly what you are after, but it is possible to make a method inside your class that would build an array of the properties you desire. You can then call that on each of the instances of the class to get the array details.
类-名为示例":
Public val1 As Variant
Public val2 As Variant
Public val3 As Variant
Public Function GetArray() As Variant
GetArray = Array(Me.val1, Me.val2, Me.val3)
End Function
客户代码-在标准模块中:
Sub SOExample()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim lst As Example, arr As Variant, key As Variant
For x = 1 To 3
Set lst = New Example
lst.val1 = "A" & x
lst.val2 = "B" & x
lst.val3 = "C" & x
dict.Add x, lst
Next
For Each key In dict.keys
arr = dict(key).GetArray
Debug.Print Join(arr, ",")
Next
End Sub
输出:
A1,B1,C1
A2,B2,C2
A3,B3,C3
这篇关于从字典返回类属性的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!