ArrayList with Arrays

三世轮回 提交于 2019-12-24 00:48:02

问题


It seems that more "complex" ArrayLists are not widely used, since I'm unable to find any concrete, helpful info about it.

I'm trying to create an ArrayList of Arrays (and eventually an ArrayList of ArrayLists of Arrays), but I seem unable to either add Arrays to the ArrayList, or access the Array's elements. All this is done using VBScript in QTP.

(The code reads from an Excel file, which is working fine.)

Set my_sheet = ExcelObject.sheets.item(testCaseSheet)
testCase     = CreateObject("System.Collections.ArrayList")

Function getTestsCaseActions (row, col)
    Do While my_sheet.cells(row, 2).Value <> ""
        MsgBox tempArray(0) & " -> " & tempArray(1) 'WORKS FINE - THE VALUES ARE PRINTED
        testCase.Add tempArray

        row = row+2
    Loop
    End Function

getTestsCaseActions 3, 4

'This is not working - how do I access the arrays and their values in the arraylist?
For Each ArrayItem in testCase
    MsgBox ArrayItem(0)' & ", " & ArrayItem(1)
    'MsgBox "Hey!"
Next

Now, I realize that For Each ArrayItem in testCase is probably wrong, but I cannot find out what to use? The elements added to the ArrayList are, after all, Arrays. If I uncomment the line MsgBox "Hey!", it's written once, even though the ArrayList should have 3 Arrays.


回答1:


Short answer: The correct way to use an ArrayList Of Arrays if you just need read access (after a successful initialization):

Option Explicit

Dim alA : Set alA = CreateObject("System.Collections.Arraylist")
alA.add Split("A B C")
alA.add Split("D E F")
alA.add Split("I J K")
WScript.Echo "---- For Each In"
Dim aX
For Each aX In alA
    WScript.Echo TypeName(aX), Join(aX)
Next
WScript.Echo "---- For To"
Dim i
For i = 0 To alA.Count - 1
    WScript.Echo TypeName(alA(i)), Join(alA(i))
Next

output:

cscript 19915175.vbs
---- For Each In
Variant() A B C
Variant() D E F
Variant() I J K
---- For To
Variant() A B C
Variant() D E F
Variant() I J K

ReDim Preserve answer(UBound(answer) + 1):

No problems with an ArrayList Of ArrayLists of Arrays (as long we are talking about read access and you don't mess it up):

Dim alB : Set alB = CreateObject("System.Collections.Arraylist")
alB.Add alA
WScript.Echo "alB(0)(0)(0) =>", alB(0)(0)(0)
WScript.Echo "alB(0)(2)(2) =>", alB(0)(2)(2)

output:

alB(0)(0)(0) => A
alB(0)(2)(2) => K


来源:https://stackoverflow.com/questions/19915175/arraylist-with-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!