我读了一篇有趣的文章here,它提出了一个有趣的观点,关于vb.net中的'case‘语句与C#中的'switch’语句,我已经粘贴到下面:
下面的Visual Basic Select Case语句不能在C#中使用单个switch语句表示:
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语句有点笨拙,在每种情况下都有下拉和中断的后续要求。有没有什么原因他们没有增强switch命令来允许这些情况?dropthrough什么时候会有用呢?有没有人知道这个结构有什么扩展可以提供更大的灵活性?
干杯
发布于 2011-05-05 08:05:36
在C#中,您只能在大小写中使用不同的值。这使得它更有局限性,但另一方面,它使它更快,因为它可以使用散列查找来实现。
在C#中,开关语法比在C/C++中受到更多的限制。你仍然可以做同样的事情,但是失败并不是隐含的,你必须编写一个具体的跳转到下一个案例。这一限制的原因是,由于错误而失败的情况比故意的要常见得多。
在C#中,您需要在默认情况下使用if语句来处理范围:
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;
}发布于 2011-05-05 08:01:32
我记得一位大学讲师曾经告诉我们,他对fall through做的唯一有用的事情就是写出圣诞节十二天的歌词。
沿着这些思路的一些东西
for (int i = 1; i <= 5; i++) {
Console.WriteLine("On the " + i + " day of christmast my true love gave to me");
switch (i) {
case 5:
Console.WriteLine("5 Gold Rings");
goto case 4;
case 4:
Console.WriteLine("4 Colly Birds");
goto case 3;
case 3:
Console.WriteLine("3 French Hens");
goto case 2;
case 2:
Console.WriteLine("2 Turtle Doves");
goto case 1;
case 1:
Console.WriteLine("And a Partridge in a Pear Tree");
break;
}
Console.WriteLine("-");
}
10年后,我倾向于同意他的观点。当时我们正在做java,它确实失败了,不得不为C#伪造它。
发布于 2011-05-05 07:54:32
对于匹配多个案例的特殊情况,允许Drop through,但不允许比较和范围案例。所以:
int condition = 55;
switch (condition) {
case 1: case 3: case 4: case 5: case 10: case 12: case 14:
// value 55 doesn't execute here anymore
default:
//values <1, 2, 6-9, 11, 13, >14
}https://stackoverflow.com/questions/5891143
复制相似问题