c语言case多种情况,switch语句中有多种情况

有没有一种方法可以遍历多个case语句而不声明case value:重复?

我知道这可行:

switch (value)

{

case 1:

case 2:

case 3:

//do some stuff

break;

case 4:

case 5:

case 6:

//do some different stuff

break;

default:

//default stuff

break;

}

但我想做这样的事情:

switch (value)

{

case 1,2,3:

//Do Something

break;

case 4,5,6:

//Do Something

break;

default:

//Do the Default

break;

}

我是从其他语言考虑使用这种语法吗?还是我错过了某些内容?

#1楼

// @詹妮弗·欧文斯(Jennifer Owens):绝对正确,以下代码无法正常工作:

case 1 | 3 | 5:

//not working do something

唯一的方法是:

case 1: case 2: case 3:

// do something

break;

您正在寻找的代码可以在Visual Basic上运行,您可以轻松地将范围放在其中...在开关的任何选项中,或者如果不方便,我建议在极端情况下使用Visual Basic制作.dll并重新导入到您的C#项目。

注意:在Visual Basic中,等效开关为选择情况。

#2楼

我想这已经被回答了。 但是,我认为您仍然可以通过以下方法以语法上更好的方式混合使用这两个选项:

switch (value)

{

case 1: case 2: case 3:

// Do Something

break;

case 4: case 5: case 6:

// Do Something

break;

default:

// Do Something

break;

}

#3楼

最初的问题有点迟了,但是我发布这个答案是希望使用较新版本( C#7-Visual Studio 2017 / .NET Framework 4.6.2中默认提供 )的人会发现它会有所帮助。

在C#7中,现在可以使用switch语句进行基于范围的切换,这将有助于解决OP的问题。

例:

int i = 5;

switch (i)

{

case int n when (n >= 7):

Console.WriteLine($"I am 7 or above: {n}");

break;

case int n when (n >= 4 && n <= 6 ):

Console.WriteLine($"I am between 4 and 6: {n}");

break;

case int n when (n <= 3):

Console.WriteLine($"I am 3 or less: {n}");

break;

}

// Output: I am between 4 and 6: 5

笔记:

在when条件中不需要括号(和) ,但是在本示例中使用括号突出显示比较。

也可以使用var代替int 。 例如: case var n when n >= 7: 。

#4楼

如果您有大量的字符串(或任何其他类型),它们都在做相同的事情,我建议结合使用string List和string.Contains属性。

因此,如果您有一个很大的switch语句,例如:

switch (stringValue)

{

case "cat":

case "dog":

case "string3":

...

case "+1000 more string": //Too many string to write a case for all!

//Do something;

case "a lonely case"

//Do something else;

.

.

.

}

您可能想要用以下if语句替换它:

//Define all the similar "case" string in a List

List listString = new List(){ "cat", "dog", "string3", "+1000 more string"};

//Use string.Contains to find what you are looking for

if (listString.Contains(stringValue))

{

//Do something;

}

else

{

//Then go back to a switch statement inside the else for the remaining cases if you really need to

}

对于任何数量的字符串情况,此缩放比例都很好。

#5楼

这是完整的C#7解决方案...

switch (value)

{

case var s when new[] { 1,2,3 }.Contains(s):

//Do Something

break;

case var s when new[] { 4,5,6 }.Contains(s):

//Do Something

break;

default:

//Do the Default

break;

}

也可以使用字符串...

switch (mystring)

{

case var s when new[] { "Alpha","Beta","Gamma" }.Contains(s):

//Do Something

break;

...

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值