• 利用Action方法委托重构switch接口


     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 }
  • 相关阅读:
    最新国家标准下载(2020-7-31)
    SL/T 264-2020 水利水电工程岩石试验规程
    SH/T 3082-2019 石油化工仪表供电设计规范
    GB/T 4780-2020 汽车车身术语
    Java——冒泡排序
    JSP处理XML数据
    JSP标准标签库(JSTL)
    千锤百炼软工第十九天
    千锤百炼软工第十八天
    千锤百炼软工第十七天
  • 原文地址:https://www.cnblogs.com/contraII/p/3123924.html
Copyright © 2020-2023  润新知