为什么要使用退出选择? [英] Why should I use exit select?

查看:15
本文介绍了为什么要使用退出选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我收集的关于退出选择的几个问题...

Here are a couple of questions I gathered regarding exit select...

  1. 是否有任何理由在 VB.NET 中使用退出选择?
  2. 原因是否与性能有关?
  3. 退出选择是否等于break;?

示例 1

Select case Name
case "Mary"
'...
case "John"
'...
case else

end select

示例 2

Select case Name
case "Mary"
'...
exit select

case "John"
'...
exit select

case else

end select

推荐答案

这与在类 C 语言中将 break 关键字与 switch 语句一起使用不同.使用 switch,如果您省略中断控制,它将进入下一个案例.使用 Visual Basic Select,控制不会失败;break 已经暗示了.

It's not the same as using the break keyword with switch statements from C-like languages. With a switch, if you omit the break control it will fall through to the next case. With a Visual Basic Select, control does not fall through; a break is already implied.

但是,您可以将其用作保护子句,以避免需要在 if 块中嵌套另一个级别的代码.例如:

However, you can use it as a guard clause, to avoid needing to nest code another level in an if block. For example:

Select Case SomeEnumVar
    Case SomeEnum.SomeValue1
         If Not SomeCondition Then Exit Select
         'Do something
    Case SomeEnum.SomeValue2
         'Do something else
    Case Else
         'Default case
End Select

这比等效的代码好一点:

That's a little nicer than this equivalent code:

Select Case SomeEnumVar
    Case SomeEnum.SomeValue1
         If SomeCondition Then
             'Do something
         End If
    Case SomeEnum.SomeValue2
         'Do something else
    Case Else
         'Default case
End Select

与其他因素相比,这两个样本之间的任何性能差异几乎可以肯定是微不足道的.

Any performance difference between these two samples is almost certainly insignificant compared to other factors.

另一种用途是如果您有很多案例,并且其中一个案例被放置以便匹配意味着您想要停止检查所有其他案例.这已经发生了,所以你可能只有一个空的 case 语句.但是您也可以添加一个 Exit Select 来向维护者表明您希望这个案例不会做任何其他事情.

One other use is if you have a lot of cases, and one of the cases is placed so that a match means you want to stop checking all the others. This already happens, and so you might just have an empty case statement there. But you might also add an Exit Select to make it clear to maintainers that you expect this case not to do anything else.

这篇关于为什么要使用退出选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆