2016-04-13 9 views
0

Ich suchte online, um herauszufinden, wie Variablennamen automatisch dynamisch deklarieren und ich kam zu keinen Ergebnissen. mein Ansatz, um den Code ist, ich bin vereinfacht wie folgt:altnitives zum dynamischen deklarieren von Variablennamen automatisch in vb.net

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

Ich wünschte, ich diese

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. 

wie folgt approch können Sie mir helfen können.

PS: Ich habe auch versucht, wie so in einem Array deklarierten Variablen zu erstellen:

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 

Antwort

0

Diese Art von Operation nicht in VB .NET (so weit unterstützt, wie ich kenne, mich zu korrigieren, wenn ich bin falsch, das macht mich klüger ...)

Sie können jedoch ein Dictionary (of String, Object) deklarieren, das die Werte enthält, die Sie behalten möchten.

Angenommen, Sie zehn Strings erstellen möchten:

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" 

Hoffe, es hilft ...

0

Traditionell wird dieses Muster adressiert unter Verwendung von Arrays. Jetzt könnten Sie Listen, Wörterbücher usw. verwenden. Die meisten Entwickler würden so etwas verwenden:

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.