C#switch语句比vb.net“案例”更有限 [英] c# switch statement more limited than vb.net 'case'

查看:125
本文介绍了C#switch语句比vb.net“案例”更有限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到一篇有趣的文章这里,它都对vb.net的案例声明VS C#中的'开关'语句,我已经粘贴下面一个有趣的问题:



下面的Visual Basic Select Case语句不能在C#中表示用一个switch语句:



<预类=朗动prettyprint-覆盖> 昏暗条件为整数= 55
选择格条件
案例1,3至5,10,12,14,是> 50
'值55执行此代码
案例否则
'值< 1,2,6-9,11,13,15至49
端选择

我总是发现C#中的switch语句,与dropthrough和consequentrequirements在每种情况下一个突破,是一个有点笨拙。没有任何理由,他们没有提高开关命令,让这些情况呢?当dropthrough是有用的呢?任何人都知道该结构的任何扩展,让更多的灵活性?



干杯


解决方案

在C#中,你只能在情况下都使用不同的值。这使得它更有限的,但在另一方面,它使得它更快,因为它可以使用一个哈希查找来实现。



开关语法已变得更受限制在C#比C / C ++。你仍然可以做同样的事情,但告吹没有隐含其中的,你必须写一个特定的跳转到下一个案例。这样做的原因的限制是,它是更为常见的做错误不是故意告吹。



在C#中,你会需要一个,如果在默认的case语句来处理范围:

  INT条件= 55; 
开关(条件){
壳体1:
壳3:
壳4:
壳体5:
壳体10:
壳体12 :
案例14:
//值1,3 - 5,10,12,14
中断;
默认:如果
(条件> 50){
//值55执行代码在这里
}其他{
//值< 1,2,6 -9,11,13,15至49
}
中断;
}


I was reading an interesting article here and it made an interesting point about the 'case' statement in vb.net vs the 'switch' statement in C#, which I've pasted below:

The following Visual Basic Select Case statement can't be represented in C# with a single switch statement:

Dim Condition As Integer = 55
Select Case Condition
  Case 1, 3 To 5, 10, 12, 14, Is > 50
    'value 55 executes code here
  Case Else
    'values <1, 2, 6-9, 11, 13, 15-49
End Select

I've always found the switch statement in C#, with dropthrough and consequentrequirements for a break in each case, to be a bit unwieldy. Is there any reason they haven't enhanced the switch command to allow these situations? When would dropthrough be useful anyway? Anyone know of any extensions of the construct to allow more flexibility?

Cheers

解决方案

In C# you can only use distinct values in cases. This makes it more limited, but on the other hand it makes it faster because it can be implemented using a hash lookup.

The switch syntax has been made more restricted in C# than in C/C++. You can still do the same things, but a fall through is not made implicitly, you have to write a specific jump to the next case. The reason for this restriction is that it's much more common to do fall through by mistake than intentionally.

In C# you would need an if statement in the default case to handle the ranges:

int condition = 55;
switch (condition) {
  case 1:
  case 3:
  case 4:
  case 5:
  case 10:
  case 12:
  case 14:
    // values 1, 3-5, 10, 12, 14
    break;
  default:
    if (condition > 50) {
      // value 55 executes code here
    } else {
      // values <1, 2, 6-9, 11, 13, 15-49
    }
    break;
}

这篇关于C#switch语句比vb.net“案例”更有限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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