用字符串vb.net动态调用变量

时间:2014-07-16 07:08:26

标签: vb.net variables dynamic

我的问题是我需要让下面的例子工作

dim player, p1cards, p2cards, ..., p6cards as integer
p1cards = 3
p2cards = 6
...
for i as integer = 1 to 6
  if ("p" & player & "cards") < 5 then
     player+=1
    "blah"
  end if
next

然而,如果(“p”&amp; player&amp;“cards”)&lt; 5然后没有做任何预期的事情。有没有办法让(“p”和“播放器”和“卡”)基本上变量,以便它可以快速,轻松地检查

2 个答案:

答案 0 :(得分:1)

可能你可以使用名为Dictionary

的东西
    Dim dict As New Dictionary(Of String, Integer)
    dict.Add("p1cards", 3)
    dict.Add("p2cards", 4)
    dict.Add("p3cards", 5)
    dict.Add("p4cards", 6)
    dict.Add("p5cards", 7)
    dict.Add("p6cards", 8)

    For Each item In dict
        If item.Value < 5 Then
            Dim aString As String = item.Key
            'do what u wan
        End If
    Next

答案 1 :(得分:0)

您可以使用List(T)存储有关播放器的更多信息(即播放器名称/卡片数量)。

Dim Player As New List(Of Object())

'initialization
For i As Integer = 0 To 5
    Player.Add(New Object() {"Player " & i + 1, 0}) 'player name / number of cards
Next i

Player(0)(1) = 3 'player 1 cards: 3
Player(1)(1) = 6 'player 2 cards: 6

'test
For i As Integer = 0 To Player.Count - 1

    Dim strName As String = Player(i)(0)
    Dim intCards As String = CInt(Player(i)(1))

    If intCards < 5 Then MsgBox(strName & " - blah")

Next i