Closed. This question is opinion-based。它当前不接受答案。
想要改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
7年前关闭。
Improve this question
考虑以下代码:
我想用switch case编写此代码:
但是我们不能用C#编写。
在知道
为了更好地匹配您的问题,您应该先对数组进行排序,然后在匹配后退出foreach:
想要改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
7年前关闭。
Improve this question
考虑以下代码:
if (results.Contains(14))
{
//anything
}
else if (results.Contains(15))
{
//anything
}
else if (results.Contains(16))
{
//anything
}
我想用switch case编写此代码:
switch (results)
{
case results.Contains(14):
}
但是我们不能用C#编写。
在知道
results
是long[]
的情况下,编写上述代码的明确方法是什么? 最佳答案
您可以在switch
中使用foreach
语句:
long[] results = new long[] { 15, 14, 16 };
foreach (long v in results)
{
switch (v)
{
case 14:
// anything
break;
case 15:
// anything
break;
case 16:
// anything
break;
}
}
为了更好地匹配您的问题,您应该先对数组进行排序,然后在匹配后退出foreach:
long[] results = new long[] { 15, 14, 16 };
Array.Sort(results);
foreach (long v in results)
{
switch (v)
{
case 14:
// anything
break;
case 15:
// anything
break;
case 16:
// anything
break;
default:
continue; // continue the foreach loop
}
break; // break the foreach loop because we had a valid match
}
关于c# - 清晰的if语句编写方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18209813/