0

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-支持选择案例统计

4

2 回答 2

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)
于 2013-08-07T04:59:48.177 回答
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
于 2013-08-07T03:28:03.650 回答