有条件地跳过案例

时间:2013-08-07 01:32:02

标签: vb.net select-case

Select...Case语句中,有没有办法根据前提条件跳过案例?

我现在在做什么,使用了一个令人难以置信的愚蠢的例子:

Private Sub PrintNumbers(includeEvenNumbers As Boolean, includeOddNumbers As Boolean)
    For number As Integer = 0 To 9
        Select Case number
            Case 0, 2, 4, 6, 8
                If includeEvenNumbers Then
                    Console.WriteLine(number)
                End If
            Case 1, 3, 5, 7, 9
                If includeOddNumbers Then
                    Console.WriteLine(number)
                End If
        End Select
    Next
End Sub

有时我甚至会把我的案子写进去:

Private Sub PrintNumbers(includeEvenNumbers As Boolean, includeOddNumbers As Boolean)
    For number As Integer = 0 To 9
        Select Case True
            Case includeEvenNumbers
                If number Mod 2 = 0 Then
                    Console.WriteLine(number)
                End If
            Case includeOddNumbers
                If number Mod 2 <> 0 Then
                    Console.WriteLine(number)
                End If
        End Select
    Next
End Sub

我真的想做的事情是:

Private Sub PrintNumbers(includeEvenNumbers As Boolean, includeOddNumbers As Boolean)
    For number As Integer = 0 To 9
        Select Case number
            Case 0, 2, 4, 6, 8 When includeEvenNumbers
                Console.WriteLine(number)
            Case 1, 3, 5, 7, 9 When includeOddNumbers
                Console.WriteLine(number)
        End Select
    Next
End Sub

请注意,我使用了When关键字,该关键字目前仅用于Try...Catch块。

可以这样做吗?我该与谁交谈以实现这一目标?

编辑(1/2)

重要的是此代码首先评估When <expression>。只有当评估结果为True时,它才会继续评估Case <expression>

我想要这样做的主要原因是因为我想编写一些情况,如果情况正确(或者错误,取决于你如何看待它),测试条件会抛出异常。如果前提条件属实,我想跳过这些案例。

编辑(2/2)

现在很清楚,在当前的VB迭代中,我所要求的是不可能的。所以我搜索了一个向.NET开发团队提交功能请求的地方,然后发现他们有一个用户语音平台。

长话短说:如果您希望实现此功能,请点按此页面上的投票按钮:https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/4274712-add-when-keyword-support-to-select-case-stat

2 个答案:

答案 0 :(得分:0)

linq的例子:

    Dim condition As Predicate(Of Integer) = Nothing
    If includeEvenNumbers Then
        condition = Function(x) x Mod 2 = 0
    Else
        condition = Function(x) x Mod 2 = 1
    End If

    For Each item In Enumerable.Range(0, 8).Where(condition)
        ' do what ever you like here...
    Next

编辑:使其更简单:

For Each item In Enumerable.Range(0, 8).Where(Function(x) x Mod 2 = If(includeEvenNumbers, 0, 1))
    ' do what ever you like here...
Next

答案 1 :(得分:0)

通过使用枚举而不是2个布尔值,您只需要一个if语句来完成2个条件检查。像这样:

Public Enum Include
    Odd = 1
    Even = 2
    Both = 0
End Enum
Private Sub PrintNumbers(includenumbers As Include)
    For I = 1 To 10
        If includenumbers = Include.Both OrElse I Mod 2 = includenumbers Mod 2 Then
            TextBox2.AppendText(I.ToString)
        End If
    Next
End Sub

你会这样称呼:

PrintNumbers(Include.Odd)