C# Switch Between Two Numbers?(C# 在两个数字之间切换?)
问题描述
我正在尝试创建一个智能 switch 语句,而不是使用 20 多个 if 语句.我试过这个
I am trying to make an intelligent switch statement instead of using 20+ if statements. I tried this
private int num;
switch(num)
{
case 1-10:
Return "number is 1 through 10"
break;
default:
Return "number is not 1 through 10"
}
它说案件不能互相失败.
It says cases cannot fall through each other.
感谢您的帮助!
推荐答案
您尝试使用 switch/case 进行范围的语法错误.
Your syntax for trying to do a range with switch/case is wrong.
case 1 - 10:
将被翻译成 case -9:
有两种方法可以尝试覆盖范围(多个值):
There are two ways you can attempt to cover ranges (multiple values):
单独列出案例
case 1: case 2: case 3: case 4: case 5:
case 6: case 7: case 8: case 9: case 10:
return "Number is 1 through 10";
default:
return "Number is not 1 though 10";
计算范围
int range = (number - 1) / 10;
switch (range)
{
case 0: // 1 - 10
return "Number is 1 through 10";
default:
return "Number is not 1 though 10";
}
但是
您确实应该考虑使用 if
语句覆盖值范围
if (1 <= number && number <= 10)
return "Number is 1 through 10";
else
return "Number is not 1 through 10";
这篇关于C# 在两个数字之间切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 在两个数字之间切换?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01