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 中的范围


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01