今天在项目中遇到了使用switch语句判断条件,但问题是条件比较多,大概有几十个条件,满屏幕的case判断,是否有更优雅的写法替代switch语句呢?

假设有这样的一个场景:商场经常会根据情况采取不同的打折方案,如果打折方案比较少,可以考虑使用switch语句作判断。但如果有几十甚至几百种打折方案的时候,用switch语句就不够优雅。

先来一个打折接口。

    public interface IValueProcessor
    {
        decimal DaZhe(short policy,decimal orginPrice);
    }

形参policy用来接收有关打折的枚举项,形参orginPrice表示打折前的价格。有关打折的枚举项为:

    public enum PolicyEnum
    {
        Wuzhe = 0,
        LiuZhe = 1,
        QiZhe =2,
        BaZhe =3,
        JiuZhe = 4
    }

实现IValueProcessor接口,根据不同的PolicyEnum项采取不同的算法。

   public class MyValueProcessor : IValueProcessor
    {
        public decimal DaZhe(short policy,decimal orginPrice)
        {
            switch (policy)
            {
                case (short)PolicyEnum.Wuzhe:
                    return orginPrice / 2;
                case (short)PolicyEnum.LiuZhe:
                    return orginPrice * (decimal)0.6;
                case (short)PolicyEnum.QiZhe:
                    return orginPrice * (decimal)0.7;
                case (short)PolicyEnum.BaZhe:
                    return orginPrice * (decimal)0.8;
                case (short)PolicyEnum.JiuZhe:
                    return orginPrice * (decimal)0.9;
                default:
                    return orginPrice / 2;
            }
        }
    }

客户端调用如下:

        static void Main(string[] args)
        {
            Console.WriteLine("请输入打折政策,0表示5折,1表示6折,2表示7折,3表示8折,4表示9折:");
            string policy = Console.ReadLine();
            decimal originPrice = (decimal)100.00;
            Console.WriteLine("打折前的价格为:"+ originPrice);

            MyValueProcessor processor = new MyValueProcessor();
            Console.WriteLine("打折后的价格为:"+ processor.DaZhe(short.Parse(policy),originPrice));
            Console.ReadKey();
        }

以上写法没有太大的问题,是否有替换switch判断,一种更优雅的写法呢?

在MyValueProcessor类的DaZhe(short policy,decimal orginPrice)方法中,接收一个short类型的形参和一个decimal类型的形参,返回decimal类型,在方法内部,把short类型的形参作为switch语句的判断条件,再使用不同的算法得到返回值。可以进一步抽象:把short类型作为字典集合中的key,把算法,即委托作为字典集合的value。这样,我们就可以把各种打折方案封装在字典集合中。修改如下:

    public class MyValueProcessor : IValueProcessor
    {
        private readonly Dictionary<short, Func<decimal, decimal>> _dic;

        public MyValueProcessor()
        {
            _dic = new Dictionary<short, Func<decimal, decimal>>
            {
                {0, m => m * (decimal)0.5},
                {1, m => m * (decimal)0.6},
                {2, m => m * (decimal)0.7},
                {3, m => m * (decimal)0.8},
                {4, m => m * (decimal)0.9}
            };
        }

        public decimal DaZhe(short policy,decimal orginPrice)
        {
            if (_dic.ContainsKey(policy))
            {
                return _dic[policy].Invoke(orginPrice);
            }
            return orginPrice / 2;
        }
    }

这样,在DaZhe(short policy,decimal orginPrice)方法内部,只要判断传入的short类型实参是否是字典集合的key就可以了。

C#中一种替换switch语句更优雅的写法的更多相关文章

  1. SQL中两种表复制语句

    Insert是T-sql中常用语句,Insert INTO table(field1,field2,...) values(value1,value2,...)这种形式的在应用程序开发中必不可少.但我 ...

  2. php中switch语句case后表达式写法记录一

    可作等级评价: $var = 95; switch(true){ case $var < 100; $level = 1; break; case $var < 95; $level = ...

  3. eclipse中更改配置使得switch语句不出错

    分别点击: windows---preference--->java---->compiler--->error/waring---->potential programmin ...

  4. MySQL比like语句更高效的写法locate position instr find_in_set

    使用内部函数instr,可代替传统的like方式查询,并且速度更快. instr函数,第一个参数是字段,第二个参数是要查询的串,返回串的位置,第一个是1,如果没找到就是0. 例如, select na ...

  5. C# 多个个Dictionary合并更优雅的写法

    Dictionary 现在有两个Dictionary的对象,想把两个对象的中数据合并成一个. 使用for循环的话觉得非常不合适,于是考虑是否有相应的方法,网上找了很多,都是for循环,最后终于找到了一 ...

  6. if else 更优雅的写法(转)

    https://www.cnblogs.com/y896926473/articles/9675819.html

  7. Python 为什么不支持 switch 语句?

    本文出自"Python为什么"系列,请查看全部文章 在这篇文章里,我们会聊一聊为什么 Python 决定不支持 switch 语句. 为什么想要聊这个话题呢? 主要是因为 swit ...

  8. 2、Golang基础--包的使用、if-else语句、循环、switch语句、数组、切片、可变函数参数、map类型

    1 包的使用 // 为了便于组织代码,同一种类型的代码,写在同一个包下,便于管理 // 定义包 -新建一个文件夹 -内部有很多go文件 -在每个go文件的第一行,都要声明包名,并且包名必须一致 -在一 ...

  9. 多路开关模式的switch语句

    在实例10中,将break语句去掉之后,会将符合检验条件后的所有语句都输出.利用这个特点,可以设计多路开关模式的switch语句,例如:在平年一年12个月,1.3.5.7.8.10.12月是31天,4 ...

随机推荐

  1. Mycat 配置及优化【转】

    前言 Mycat 是一个数据库分库分表中间件 MyCAT 是作为通用代理设计的,后端是以 Mysql协议 和 JDBC 的方式连接数据库,可以支持 Oracle.DB2.SQL Server . mo ...

  2. 不能访问本地服务器场。没有注册带有FeatureDependencyId 的 Cmdlet

      不能访问本地服务器场.没有注册带有FeatureDependencyId 的 Cmdlet. 原因: 我有两个域管理员账号,分别:sp\administrator,sp\spadmin 其中后者才 ...

  3. 虚拟机Failed to start LSB: Bring up/down networking

      1.执行 service network restart 出现以下错误 Restarting network (via systemctl):  Job for network.service f ...

  4. laravel 5.1 Model 属性详解

    <?php namespace Illuminate\Database\Eloquent; /** * 下面提到某些词的含义: * 1.覆盖: 在继承该类 \Illuminate\Databas ...

  5. sqlmap工作流程图

  6. 有没有 linux 命令可以获取我的公网 ip, 类似 ip138.com 上获取的 ip?

    curl ipinfo.iocurl ifconfig.me 阿里云 :139.129.242.131赤峰:   219.159.38.197开平:   221.194.113.146定州:  121 ...

  7. android:怎么实现一个控件与另一个指定控件左对齐

    https://segmentfault.com/q/1010000003905460?_ea=425861 针对你这种情况,最简单的一种办法是,设置两个TextView的宽度为固定值,且相等. Li ...

  8. hdu 5443 (2015长春网赛G题 求区间最值)

    求区间最值,数据范围也很小,因为只会线段树,所以套了线段树模板=.= Sample Input3110011 151 2 3 4 551 21 32 43 43 531 999999 141 11 2 ...

  9. day11--RabbitMQ、Redis

        RabbitMQ:就是消息队列与Python里面的queue功能类似.线程和进程queue只能Python自己使用:不同机器和程序传递消息就要使用RabbitMQ了,中间传递. RabbitM ...

  10. React 与 Redux 在生产环境中的实践总结

    React 与 Redux 在生产环境中的实践总结 前段时间使用 React 与 Redux 重构了我们360netlab 的 开放数据平台.现将其中一些技术实践经验总结如下: Universal 渲 ...