从数组创建动态变量 [英] Create dynamic Variables from an Array
问题描述
好的,所以我想使用数组中的名称将动态变量创建为整数.这是我迄今为止尝试过的:
Ok, so i want to create dynamic Variables as Integer using the names from an Array. This is what I've tried so far:
Dim subjects as Array {"Math", "English", "German"} 'Three example names
Dim subjectsInt as New Dictionary(Of Integer) 'Throws error: Not enough arguments
Dim i as Integer
For i = 0 to 2
subjectsInt(subjects(i)) = 0 ' Trying to create a variable with the name of entry number i of the Array & and the starting value 0
Do
Console.WriteLine(subjects(1) & ": ")
Dim input As String = Console.ReadLine()
subjectsInt = CInt(input)
Loop While subjectsInt = 0 Or subjectsInt > 100
Next i
最后我想要这样的结果:
in the end I want a result like this:
Math = 10 'random values between 1 and 100
English = 40
German = 90
我希望我的问题足够清楚,提前致谢:)
I hope my question is clear enough, thanks in advance :)
推荐答案
你说得对,没有足够的论据.一本字典,更具体地说是 Dictionary(Of TKey, TValue)
,接受键类型的参数和将要使用的值类型.
You're quite right that there's not enough arguments. A dictionary, more specifically a Dictionary(Of TKey, TValue)
, takes an argument for the type of key and the type of value it is going to use.
如果您希望它使用您的字符串进行查找,您必须将第一个类型设为 String
:
As you want it to use your strings for lookup you would have to make the first type a String
:
Dim subjectsInt As New Dictionary(Of String, Integer)
这将使您能够通过执行以下操作来访问值:
This will make you able to access the values by doing:
subjectsInt(<your string here>)
'Example:
subjectsInt("Math")
subjectsInt(subjects(0)) 'The first string (which is "Math") from the 'subjects' array.
虽然您必须确保先添加密钥,但您只能添加一次:
Though you must be sure to add the key first, but you may only add it once:
subjectsInt.Add("Math", <your initial value here>)
'You may use strings any way you can access them, for example:
subjectsInt.Add(subjects(0), <your initial value here>)
subjectsInt.Add(subjects(i), <your initial value here>)
'etc...
那么你应该能够根据需要获取/设置它:
Then you should just be able to get/set it as you wanted:
subjectsInt(subjects(i)) = CInt(input)
这篇关于从数组创建动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!