从数组创建动态变量

时间:2016-07-10 11:11:25

标签: vb.net

好的,所以我想使用Array中的名称创建动态变量作为整数。这是我到目前为止所尝试的:

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

最后我想要一个这样的结果:

Math = 10       'random values between 1 and 100
English = 40
German = 90

我希望我的问题很清楚,提前谢谢:)

2 个答案:

答案 0 :(得分:1)

你没有足够的论据,你说得对。字典,更具体地说是Dictionary(Of TKey, TValue),为密钥类型及其将使用的值类型提供参数。

如果您希望它使用您的字符串进行查找,您必须将第一个类型设为String

Dim subjectsInt As New Dictionary(Of String, Integer)

这样您就可以通过执行以下操作来访问这些值:

subjectsInt(<your string here>)

'Example:
subjectsInt("Math")
subjectsInt(subjects(0)) 'The first string (which is "Math") from the 'subjects' array.

虽然您必须先确保添加密钥,但您只能添加一次:

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...

然后你应该能够得到/设置它:

subjectsInt(subjects(i)) = CInt(input)

答案 1 :(得分:0)

您可以尝试这样的事情:

Sub Main()

    Dim dic As New Dictionary(Of String, Integer) From {{"Math", 10}, {"English", 40}, {"German", 90}}

    For Each entry In dic.Keys
        Console.WriteLine(String.Format("{0}: {1}", entry, dic(entry)))
    Next

    Console.ReadKey()

End Sub