我知道我无法动态引用变量(例如'var& var.Close()')。 我可以以某种方式拥有一个可以通过名称指向另一个变量的变量吗?
我当前的代码是(其中func()需要一个数组):
Dim playerNum As String = “P1”
Select Case playerNum
Case “P1”
Func(P1(x, xx))
Case “P2”
Func(P2(x, xx))
.........
End Select
这些方面可以做些什么吗?
Dim playerNum As varNameRef = P1(,)
Func(playerNum(x, xx))
真的有什么能阻止这么多的重复将非常感激。 欢呼声。
答案 0 :(得分:1)
你可以通过反思来做到这一点,但我会建议反对性能,可读性和可维护性原因。
如果您真的需要,可以使用Actions(Of T)
,例如:
Class Player
Public Name As String
End Class
Sub play(player As Player)
Console.WriteLine(player.Name & " plays now")
End Sub
创建一些演示者来演示:
Dim playerList As New List(Of Player)
For i As Int32 = 1 To 10
Dim p = New Player() With {.Name = "P" & i}
playerList.Add(p)
Next
playerList.ForEach(AddressOf play)
答案 1 :(得分:1)
您需要的是引用类型(类),而不是值类型(结构)。例如,如果您创建了一个将数组存储为属性的类,如下所示:
Public Class PlayerData
Public Data(10, 30) As Object
End Class
这也为您提供了轻松扩展存储在每个播放器上的数据的优势。然后,您可以使用多个变量引用相同的PlayerData
对象:
Dim player1 As New PlayerData()
Dim player2 As New PlayerData()
Dim player As PlayerData = Nothing
Select Case playerNum
Case “P1”
player = player1
Case “P2”
player = player2
End Select
Func(player.Data(x, xx))
然而,将它们作为键值对存储在字典中会更好,例如:
Dim players As New Dictionary(Of String, PlayerData)()
players("P1") = New PlayerData()
players("P2") = New PlayerData()
然后,您可以访问这样的玩家:
Func(players(playerNum).Data(x, xx))