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


- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01