在VB.NET中我为什么要使用Select而不是If? [英] In VB.NET why should I use Select, instead of If?

查看:111
本文介绍了在VB.NET中我为什么要使用Select而不是If?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚毕业并开始了一份真正的工作。在我们的培训中,他们一直在向我们展示VB.NET以及他们在这里使用的许多功能。在一些例子中,他们使用了选择语句(并且在一些地方使用了 If / Else 确实应该使用过。)

I've recently graduated and started a real job. In our training they've been exposing us to VB.NET and a lot of the features they use here. In some of the examples, they've used Select statements (and in a few places they were used where an If/Else really should have been used).

我唯一一次在其他语言中使用switch / select语句(除了需要它的赋值)当我想要落到下一个声明时。

The only time that I've used a switch/select statement in other languages (other than assignments that required it) has been when I wanted the fall through to the next statement.

鉴于VB.NET没有失败,有什么(如果有的话)使用选择声明?有什么情况下它提供的优势超过 If / ElseIf 声明?

Given than VB.NET has no fall through, what (if any) cases are there to use the Select statement? Are there any cases when it provides advantages over and If/ElseIf statement?

推荐答案

选择案例,而不仅仅是选择

对我而言,这是该语言的最佳功能之一。

Select Case, not just Select.
To me, it's one of the best features of the language.


  1. 当您有几个可能的值进行测试时,它会更直观。

  1. It's much more visual when you have several possible values to test against.

select case some_var
case 1
  something()
case 2
  something_else()
case 3
  etc()
end select


  • 在测试范围时,它的可读性更高:

  • It's much more readable when it comes to testing ranges:

    select case some_var
    case 1 to 10
      something()
    case 20 to 30
      something_else()
    case is > 100
      etc()
    end select
    


  • 它更具可读性当你有一堆更复杂的条件要测试时,确保只选择一个:

  • It's much more readable when you have a bunch of more complex conditions to test, making sure only one is selected:

    select case true
    case string.isnullorempty(a_string)
      something()
    case a_string.length < 5
      something_else()
    case a_string = b_string
      etc()
    end select
    


  • 它优于C / C ++ switch ,因为它允许表达式作为分支点,而不仅仅是常量。

  • It's superior to C/C++ switch in the sense that it allows expressions as branching points, not just constants.

    当使用常量作为分支点(示例1)时,编译器能够使用直接跳转生成更优化的代码。

    When using constants as branching points (example 1), compiler is able to generate a more optimised code with direct jumps.

    这篇关于在VB.NET中我为什么要使用Select而不是If?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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