选择各种输入金额的大小写

时间:2015-05-16 22:46:30

标签: arrays vb.net function for-loop select-case

这是我到目前为止所拥有的;

    Function myChoice(ByVal opt1 As String, ByVal opt2 As String, ByVal opt3 As String, ByVal opt4 As String)

    Dim choose As String
    Dim mynum As Integer

    Randomize()
    mynum = Int(Rnd() * 4 + 1)

    Select Case mynum
        Case 1
            choose = opt1
        Case 2
            choose = opt2
        Case 3
            choose = opt3
        Case 4
            choose = opt4
    End Select

    myChoice = choose

End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    MsgBox(myChoice("Red", "Orange", "Yellow", "Green"))

End Sub

我想做的是没有ByVal opt1作为字符串,ByVal op2 ..... 如果我说100种颜色,我该如何使该功能有100个选项,并且100' case'事件没有全部输入?

我可能需要一个循环,也许是一个数组,但除此之外,我很难过。

感谢。

1 个答案:

答案 0 :(得分:1)

首先使用ParamArray参数。然后使用Random类来获取随机项。如果您打算在短时间内多次调用此方法,我会使用最顶层的。

Function ChooseOne(ParamArray opts() As String)
  Static rnd As New Random
  Return opts(rnd.Next(0, opts.Count))
End Function

还是更简单!

Function ChooseOne(ParamArray opts() As String)
  Return opts(New Random().Next(0, opts.Count))
End Function