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