切换机箱,检查C#3.5中的范围

Ken*_*nny 12 c# switch-statement

在C#中,switch语句不允许案例跨越值范围.我不喜欢为此目的使用if-else循环的想法,所以有没有其他方法来检查C#中的数值范围?

slo*_*oth 16

您可以HashTable分别使用a Dictionary来创建映射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();
    }
}
Run Code Online (Sandbox Code Playgroud)

此技术是一种常规替代方法switch,尤其是如果操作仅包含一行(如方法调用).

如果你是类型别名的粉丝:

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") } 
    };
Run Code Online (Sandbox Code Playgroud)

  • 但是你不应该拿一本字典(取一个KeyValuePair,Tuple或者自定义的列表),否则你无法预测调用Funcs的顺序. (2认同)

Mar*_*ell 5

不.当然,如果范围很小,你可以使用

case 4:
case 5:
case 6:
   // blah
   break;
Run Code Online (Sandbox Code Playgroud)

方法,但除此之外:没有.使用if/ else.