Why should I use exit select?

[亡魂溺海] 提交于 2019-12-05 12:53:13

问题


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

  1. Is there any reason for using exit select in VB.NET?
  2. Does the reason have anything to do with performance?
  3. Is the exit select equal to break;?

Example 1

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

end select

Example 2

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

case "John"
'...
exit select

case else

end select

回答1:


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.

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.

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.




回答2:


Well... It is like using a goto... Once you found the correct case there is no use in "exiting" the case since in Visual Basic it will be going out. In C# you need to exit the case (in that case, with a break).

The point is that you can use it in the middle of the scope of a case, something like:

Case 1
   Do something
   Do something
   Evaluate
      exit select
   Else
      Do something

It's ugly, but you can do that...



来源:https://stackoverflow.com/questions/1924128/why-should-i-use-exit-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!