使用循环调用多个对象/变量“名称”

时间:2013-06-14 16:09:02

标签: vb.net visual-studio-2008

我不得不在循环中将这些变量添加到ComboBox,我想用循环更简单的方式调用它,但我失败了很多次,我一直在谷歌搜索但我仍然失败,所以任何帮助将不胜感激

Public MyPass1 As String = "John"
Public MyPass2 As String = "Andrew"
Public MyPass3 As String = "Stewart"
Public MyPass4 As String = "Meiny"
Public MyPass5 As String = "Franco"
Public MyPass6 As String = "Hanks"
Public MyPass7 As String = "Buzz"
Public MyPass8 As String = "Timmy"
Public MyPass9 As String = "George"
Public MyPass10 As String = "Sanders"

Sub Putitem(ByVal MyPass)
    With cmbAsk
        For i As Integer = 0 To 9
            Dim c As Integer
            c = i + 1
            Items.Add(MyPass(c)) 'The main problem is here, i want to do looping for calling it.
            i = c
        Next
    End With
End Sub

任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以将它们存储在数组中,而不是将值存储在单个变量中:

Public MyPasses As String() = New String() { 
                             "John",
                             "Andrew",  
                             "Stewart",
                             "Meiny",
                             "Franco",
                             "Hanks",
                             "Buzz",
                             "Timmy",
                             "George",                               
                             "Sanders"
                          }

然后您可以通过以下方式访问:

Items.Add(MyPasses(c))

答案 1 :(得分:1)

您需要一个集合来添加非公共字符串。

Private collection() As String = {"John", "Mark", "Frank"} 'initializer

cmbAsk.Items.AddRange(collection.ToArray)

AddRange method