zoukankan      html  css  js  c++  java
  • 关于使用枚举作为索引的优化

    关于使用枚举作为索引的优化

    看了别人的博客学的,记录下,留用!

    源代码

    enum TemplateCode
    {
        None = 0,
        Head = 1,
        Menu = 2,
        Foot = 3,
        Welcome = 4,
    }
    
    public string GetHtml(TemplateCode tc)
    {
        switch (tc)
        {
            case TemplateCode.Head:
                return GetHead();
            case TemplateCode.Menu:
                return GetMenu();
            case TemplateCode.Foot:
                return GetFoot();
            case TemplateCode.Welcome:
                return GetWelcome();
            default:
                throw new ArgumentOutOfRangeException("tc");
        }
    }
    

    优化后

    		public enum TemplateCode
            {
                Head = 1,
                Menu = 2,
                Foot = 3,
                Welcome = 4
            }
            public string GetHtml(TemplateCode tc, string msg)
            {
                Func<string, string> func;
                if (TemplateDict.TryGetValue(tc, out func))
                {
                    return func(msg);
                }
                return "do nothing";
            }
            public readonly static Dictionary<TemplateCode, Func<string, string>> TemplateDict = InitTemplateFunction();
    
            private static Dictionary<TemplateCode, Func<string, string>> InitTemplateFunction()
            {
                var ditc = new Dictionary<TemplateCode, Func<string, string>>();
                ditc.Add(TemplateCode.Head, GetHead);
                ditc.Add(TemplateCode.Menu, GetMenu);
                ditc.Add(TemplateCode.Foot, GetFoot);
                ditc.Add(TemplateCode.Welcome, GetWelcome);
                return ditc;
            }
            public static string GetHead(string msg)
            {
                return msg + "a";
            }
            public static string GetMenu(string msg)
            {
                return msg + "b";
            }
            public static string GetFoot(string msg)
            {
                return msg + "c";
            }
            public static string GetWelcome(string msg)
            {
                return msg + "d";
            }
    

    这种优化在分支比较多的时候很好用,少的时候作用有限

  • 相关阅读:
    Oracle86和92语法的连接,子查询,集合的操作
    Oracle笛卡尔积,分组,多表连接
    Oracle排序,伪列,字符函数,数字函数,日期行数
    Oracle基本的数据类型以及简单sql查询
    用while语句打印阶乘
    Switch小练习
    if语句多表达式与一个表达式
    三元操作符
    整数的二进制表达
    与或
  • 原文地址:https://www.cnblogs.com/zhubangchao/p/8086564.html
Copyright © 2011-2022 走看看