Select 各种输入量的案例

Select case for various input amounts

这是我目前所拥有的;

    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' 事件而不用全部输入?

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

谢谢。

首先利用ParamArray parameter. Then use the Randomclass获得随机物品。如果你要在短时间内多次调用这个方法,我会使用上面的那个。

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