Switch case, check ranges in C# 3.5

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#?


You can use a HashTable respectively Dictionary to create a mapping of Condition => Action .

Example:

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).

And if you're a fan of type aliases:

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

Nope. Of course, if the ranges are small you could use the

case 4:
case 5:
case 6:
   // blah
   break;

approach, but other than that: no. Use if / else .


if the interval of the ranges is constant, you can try

        int num = 11;
        int range = (num - 1) / 10; //here interval is 10
        switch (range)
        {
            case 0:
                Console.Write("1-10");
                break; // 1-10
            case 1:
                Console.Write("11-20");
                break; // 11-20
            // etc...
        }

Output would be: "11-20"
if interval is variable then use if/else

链接地址: http://www.djcxy.com/p/84452.html

上一篇: case / switch语句c#?

下一篇: 切换大小写,检查C#3.5中的范围