在 vb.net 中自动动态声明变量名的替代方法

alturnitives to dynamicly declaining variable names automaticly in vb.net

我在网上搜索如何自动动态声明变量名,但没有找到任何结果。我对正在简化的代码的处理方法如下:

dim choice1 as string
dim choice2 as string
dim choice3 as string
...

我希望我能按如下方式处理这个问题

dim count as integer
while count is 1 to 10
   count +=1
end while
dim (choice+count) as string
' it suppose to create variable choice with the addition to the name from 1    to 10 like choice1, choice2, choice3 and so on.

你能帮帮我吗

ps:我也试过像这样在数组中创建声明的变量:

dim count as integer
Dim var As Array = {Dim choice1 as string, dim choice2 as string}
while count is 1 to 10
     var.add(dim choice+count as string)
end while

VB.NET 不支持这种操作(据我所知,如果我错了,请纠正我,这会让我更聪明...)

但是,您可以声明一个 Dictionary(of String, Object) 来保存您想要保留的值。

假设您要创建十个字符串:

Dim myvars as New Dictionary(of String, String)

For i = 1 to 10
  myVars.Add("choice" & i, "New String Value")
Next

'Next you can access these vars like this
Dim choice = "choice5"
Dim string5 = myVars(choice)
myvars(choice) = "Replaced"

希望对您有所帮助...

传统上,这种模式是使用数组来解决的。现在你可以使用列表、字典等。大多数开发人员会使用这样的东西:

Dim choice(10) as String
'choice(0) is same as choice0
'choice(1) is same as choice1
'choice(2) is same as choice2
'choice(3) is same as choice3
'etc.