1 using System; 2 using System.Collections.Generic; 3 4 namespace ConsoleApplication1 5 { 6 internal class Program 7 { 8 private static void Main(string[] args) 9 { 10 while (true) 11 { 12 var s = Console.ReadLine(); 13 int i; 14 int.TryParse(s,out i); 15 16 //swtich分支处理 17 switch (i) 18 { 19 case 1: 20 MethodHelper.A(); 21 break; 22 case 2: 23 MethodHelper.B(); 24 break; 25 case 3: 26 MethodHelper.C(); 27 break; 28 } 29 30 //委托处理 31 ActionDic.GetInstance().DoAction(i); 32 } 33 } 34 } 35 36 public class MethodHelper 37 { 38 public static void A() 39 { 40 Console.WriteLine("A"); 41 } 42 public static void B() 43 { 44 Console.WriteLine("B"); 45 } 46 public static void C() 47 { 48 Console.WriteLine("C"); 49 } 50 } 51 52 public sealed class ActionDic 53 { 54 private static readonly ActionDic instance = new ActionDic(); 55 56 private ActionDic() 57 { 58 actList = new Dictionary<int, Action> 59 { 60 {1, MethodHelper.A}, 61 {2, MethodHelper.B}, 62 {3, MethodHelper.C}, 63 }; 64 } 65 public static ActionDic GetInstance() 66 { 67 return instance; 68 } 69 private readonly Dictionary<int, Action> actList; 70 71 public void DoAction(int act) 72 { 73 Action ar; 74 if (actList.TryGetValue(act, out ar)) 75 { 76 ar.Invoke(); 77 } 78 } 79 } 80 }