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";
            }
    

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

  • 相关阅读:
    C#冒泡排序--详解
    盘古搜索--实例解析
    ajax提交表单序列化(serialize())数据
    随机数大揭秘
    静态代码块(主要是注意执行顺序)
    单例模式
    递归
    vue路由嵌套(邹文丰)
    vue computed和 methods、 watch 区别(邹文丰)
    vuex状态管理mutations,getters,actions总结(邹文丰)
  • 原文地址:https://www.cnblogs.com/zhubangchao/p/8086564.html
Copyright © 2011-2022 走看看