转而在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(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.

最新更新