本文介绍了切换大小写,检查 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 中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!