【问题标题】:dynamicaly calling variables with strings vb.net使用字符串动态调用变量 vb.net
【发布时间】:2014-09-06 14:25:06
【问题描述】:

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

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" & player & "cards")

【问题讨论】:

  • 所以..一个完整而清晰的问题?
  • 对每个整数使用选择大小写。
  • 您需要将值存储在不同的数据结构中,而不是单个变量,然后您可以循环或枚举。就像一个数组或列表。如果确实需要任意构建一个“唯一键”,可以使用哈希表或字典。

标签: vb.net variables dynamic


【解决方案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

【讨论】:

    【解决方案2】:

    您可以使用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
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 2011-02-17
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多