Using VB I can create and access a random "cell" in an array like so
Dim array(5) as array
Dim r as new random
r.next(0,5)
array(r) will then access a random 开发者_如何转开发"cell" based upon r's value.
Is there a way to say something like button(r) to directly randomize which button is chosen instead of having to use a random and If's like so?
r.next(0,5)
If r = 1 then
button1 ...
elseif r = 2
button 2 ...
end if
Using an array of Button is the superior solution. But you can do it cheap by choosing the button names carefully:
Dim btn as Button = DirectCast(Me.Controls("Button" + r.Next(6).ToString()), Button)
Note that I used 6. arrButtons(5) contains 6 elements at indices 0 through 5.
You can make an array of buttons, like this:
'In your class
Dim buttons() As Button
Dim rand as New Random()
Public Sub New()
InitializeComponent()
buttons = New Button() { Button1, Button2, ... }
End Sub
'Somewhere else:
Dim randomButton As Button = buttons(rand.Next(buttons.Length))
If you have an array of buttons, sure you can.
Looking at your codes, seems like you are refering to VB.NET.
Dim r as New Random(someSeed)
Dim arrButtons(5) As Button
'assign the buttons to the array
'.....
Dim chosenButton As Button = Buttons(r.Next(0,arrButtons.Length))
精彩评论