【问题标题】:alturnitives to dynamicly declaining variable names automaticly in vb.net在 vb.net 中自动动态声明变量名的替代方法
【发布时间】:2016-08-04 16:40:09
【问题描述】:

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

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

【问题讨论】:

    标签: arrays vb.net variables dynamic naming


    【解决方案1】:

    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"
    

    希望对你有帮助...

    【讨论】:

      【解决方案2】:

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

      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.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-14
        • 2016-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多