Switch case, check ranges in C# 3.5
在c_中,
可以分别使用
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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(); } } |
此技术是
如果你喜欢别名类型:
1 2 3 4 5 6 7 8 | 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") } }; |
不。当然,如果范围小,可以使用
1 2 3 4 5 | case 4: case 5: case 6: // blah break; |
方法,除此之外:不使用
如果范围的间隔是常量,您可以尝试
1 2 3 4 5 6 7 8 9 10 11 12 | 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... } |
输出为:
如果间隔是可变的,则使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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; |
试试这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | private void ExecuteInRange(Dictionary<Range,Action<int>> 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
一种嵌套的速记法,如果其他东西起作用,而且是干净的。
1 | myModel.Value = modelResult >= 20 ? 5 : modelResult >= 14 ? 4 : modelResult >= 5 ? 3 : modelResult >= 2 ? 2 : modelResult == 1 ? 1 : 0; |