开关的情况下,检查范围在C#3.5 [英] Switch case, check ranges in C# 3.5

查看:115
本文介绍了开关的情况下,检查范围在C#3.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,开关语句不允许的情况下跨越的值范围。我不喜欢使用的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 分别为词典以创建条件= GT; 。操作

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();
    }
}

这技术是一个普通的替代开关,特别是如果操作只包括一行(类似方法调用)。

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆