c# switch 语句比 vb.net 'case' 更受限制
我正在此处阅读一篇有趣的文章它提出了一个关于 vb.net 中的“case”语句与 C# 中的“switch”语句的有趣观点,我将其粘贴在下面:
以下 Visual Basic Select Case 语句不能用单个 switch 在 C# 中表示语句:
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
我总是发现 C# 中的 switch 语句,在每种情况下都带有 dropthrough 和随后的中断要求,有点笨拙。他们有什么理由没有增强 switch 命令来允许这些情况吗?到底什么时候 dropthrough 会有用呢?有人知道该结构的任何扩展以提供更大的灵活性吗?
干杯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C# 中,只能在情况下使用不同的值。这使得它更加受到限制,但另一方面它使它变得更快,因为它可以使用哈希查找来实现。
C# 中的 switch 语法比 C/C++ 中的限制更严格。您仍然可以做同样的事情,但是不会隐式地进行失败,您必须编写到下一个案例的特定跳转。之所以有这样的限制,是因为错误地摔倒比故意摔倒更常见。
在 C# 中,默认情况下您需要一个 if 语句来处理范围:
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:
我记得一位大学讲师曾经告诉我们,他发现应对失败的唯一有用的事情就是写下圣诞节十二天的歌词。
沿着这些思路
10年后我开始同意他的观点。当时我们正在做java,但确实失败了,不得不为C#伪造它。
I remember a uni lecturer once telling us the only useful thing he had ever found to do with fall through was write out the lyrics to the twelve days of christmas.
Something along these lines
10 years later I tend to agree with him. At the time we were doing java which does fall through, had to fake it for C#.
对于匹配多个案例的特殊情况,允许直接删除,但不允许比较和范围案例。所以:
Drop through is allowed for the special case of matching multiple cases, but the comparative and range cases aren't allowed. So: