简体   繁体   中英

Convert string to pre-defined variable name in Visual Basic?

I'm programming a basic slot machine in Visual basic, and want to use a for loop to randomly choose the image for each slot, display the image in each slot, and change the slotName variable (so I can check later on which symbols are in the slots) for each slot.

The problem I'm finding with a for loop is that the variables and objects for each slot have different names (slot1Name, slot2Name, slot3Name, lblSlot1, lblSlot2, lblSlot3, etc). Is there any way I could have something like:

currentSlotName = "slot" & i & "Name"

This is the code at the moment, this code is repeated (with different variable and object names), for each of the 3 slots, which is pretty inefficient. How can I tidy this code up?

' Randomise numbers and assign images to slots based on random numbers, if the hold isn't on
    ' Slot 1
    If Not held1 Then
        slot1Value = Int(Rnd() * numbersGenerated + 0.5)
        Select Case slot1Value
            Case 0 To 5
                lblSlot1.Image = imgBanana
                slot1Name = "Banana"
            Case 6 To 11
                lblSlot1.Image = imgOrange
                slot1Name = "Orange"
            Case 12 To 16
                lblSlot1.Image = imgCherries
                slot1Name = "Cherries"
            Case 17 To 19
                lblSlot1.Image = imgSeven
                slot1Name = "Seven"
            Case 20
                lblSlot1.Image = imgBatman
                slot1Name = "Batman"
            Case Else
                lblSlot1.Text = "Error. slot1value = " & slot1Value
        End Select
    End If

I have searched around for this, but I'm very new to Visual Basic, and want to keep my code as simple as possible.

Too much to explain. Arrays is what you need to learn next.

http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM