Switch case, check ranges in C# 3.5(切换大小写,检查 C# 3.5 中的范围)
问题描述
在 C# 中,switch 语句不允许 case 跨越值的范围.我不喜欢为此使用 if-else 循环的想法,那么还有其他方法可以检查 C# 中的数字范围吗?
In C#, the switch statement doesn't allow cases to span ranges of values. I don't like the idea of using if-else loops for this purpose, so are there any other ways to check numeric ranges in C#?
推荐答案
可以使用一个HashTable分别Dictionary来创建Condition =>的映射;动作.
You can use a HashTable respectively Dictionary to create a mapping of Condition => Action.
例子:
class Programm
{
static void Main()
{
var myNum = 12;
var cases = new Dictionary<Func<int, bool>, Action>
{
{ x => x < 3 , () => Console.WriteLine("Smaller than 3") } ,
{ x => x < 30 , () => Console.WriteLine("Smaller than 30") } ,
{ x => x < 300 , () => Console.WriteLine("Smaller than 300") }
};
cases.First(kvp => kvp.Key(myNum)).Value();
}
}
这种技术是 switch 的一般替代方法,尤其是当操作仅包含一行时(如方法调用).
This technique is a general alternative to switch, especially if the actions consists only of one line (like a method call).
如果你喜欢类型别名:
using Int32Condition = System.Collections.Generic.Dictionary<System.Func<System.Int32, System.Boolean>, System.Action>;
...
var cases = new Int32Condition()
{
{ x => x < 3 , () => Console.WriteLine("Smaller than 3") } ,
{ x => x < 30 , () => Console.WriteLine("Smaller than 30") } ,
{ x => x < 300 , () => Console.WriteLine("Smaller than 300") }
};
这篇关于切换大小写,检查 C# 3.5 中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:切换大小写,检查 C# 3.5 中的范围
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
