切换案例,检查C#3.5中的范围

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

您可以分别使用HashTable Dictionary来创建Condition => Action的映射。

例:

 class Programm { static void Main() { var myNum = 12; var cases = new Dictionary, 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的一般替代方法,尤其是如果操作仅包含一行(如方法调用)。

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

 using Int32Condition = System.Collections.Generic.Dictionary, 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") } }; 

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

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

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

如果范围的间隔是不变的,你可以试试

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

输出将是: "11-20"
如果interval是可变的,那么使用if/else

尝试这样的事情

  private void ExecuteInRange(Dictionary> ranges) { foreach (var range in ranges) { if (range.Key.Value < range.Key.Max && range.Key.Value > range.Key.Max) range.Value(range.Key.Value); } } public class Range { public int Min { get; set; } public int Max { get; set; } public int Value { get; set; } } 

不,至少没什么更美的。

此外,没有C#3.5只有.NET 3.5和C#3.0

  int b; b = Int32.Parse(textBox1.Text); int ans = (100-b)/3; //the 3 represents the interval //100 represents the last number switch(ans) { case 0: MessageBox.Show("98 to 100"); break; case 1: MessageBox.Show("95 to 97"); break; case 2: MessageBox.Show("92 to 94"); break; case 3: MessageBox.Show("89 to 91"); break; case 4: MessageBox.Show("86 to 88"); break; default: MessageBox.Show("out of range"); break; 

一种嵌套的简写if-else的东西是有效的,而且很干净。

 myModel.Value = modelResult >= 20 ? 5 : modelResult >= 14 ? 4 : modelResult >= 5 ? 3 : modelResult >= 2 ? 2 : modelResult == 1 ? 1 : 0;