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# 在两个数字之间切换?
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
