问题
Is there way I can declare 70 different variables in a loop instead of declaring each one?
I wanted to do something like below:
For i As Integer = 0 To 70
Dim Para + i AS OracleParameter
Next
Instead of declaring as below:
Dim Param1 AS OracleParameter
Dim Param2 AS OracleParameter
Dim Param3 AS OracleParameter
…
Dim Param70 AS OracleParameter
回答1:
Use an array:
Dim Param(69) As OracleParameter
For i As Integer = 0 To Param.Length - 1
Param(i) = New OracleParameter(..)
'' etc..
Next
回答2:
I have never seen such a method, but in looking at it, why wouldn't you use a list or a KeyValuePair using the index as the key? I would really recommend using something of that nature, even if you keep the word "Param" as part of the key.
Dim Parameters as New KeyValuePair(Of String, OracleParameter)
For i AS Integer = 0 To 70
Parameters.Add("Param" & i.ToString(), New OracleParameter)
Next
This could then be accessed at any time using (e.g.)
Parameters("Param66").Value
回答3:
Normally this is done by using an array:
Dim Para(70) As OracleParameter
To access an element of the array use Para(0), Para(1) and so on.
If you actually need seperate variables you could write a small programm that prints out the needed code lines and copy&paste these to your code file - but I don't see any reason for doing so :-)
Bye, Jens
来源:https://stackoverflow.com/questions/8592351/declaring-variable-dynamically-in-vb-net