Dynamically create variables in VB.NET

后端 未结 3 1452
醉话见心
醉话见心 2021-01-06 01:04

I have been trying to figure this out for some time now and can\'t seem to figure out an answer to it. I don\'t see why this would be impossible. I am coding in VB.NET.

相关标签:
3条回答
  • 2021-01-06 01:22

    You want to use a List

    Dim Numbers As New List(Of Integer)
    
    For i As Integer = 0 To 9 
        Numbers.Add(0)
    Next
    

    The idea of creating a bunch of named variables on the fly is not something you are likely to see in any VB.Net program. If you have multiple items, you just store them in a list, array, or some other type of collection.

    0 讨论(0)
  • 2021-01-06 01:24

    The best way to do something like this is with the Dictionary(T) class. It is generic, so you can use it to store any type of objects. It allows you to easily store and retrieve code/value pairs. In your case, the "key" would be the variable name and the "value" would be the variable value. So for instance:

    Dim variables As New Dictionary(Of String, Integer)()
    variables("MyDynamicVariable") = 10  ' Set the value of the "variable"
    Dim value As Integer = variables("MyDynamicVariable")  ' Retrieve the value of the variable
    
    0 讨论(0)
  • 2021-01-06 01:24

    'Dim an Array Dim xCount as Integer Dim myVar(xCount) as String

    AddButton Event . . . xCount += 1 myVar(xCount) = "String Value"

    'You will have to keep Track of what xCount Value is equal to to use. 'Typically could be an ID in A DataTable, with a string Meaning

    0 讨论(0)
提交回复
热议问题