今天在项目中遇到了使用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. 字符串格式化(百分号&format)

    字符串格式化 Python的字符串格式化有两种方式: 百分号方式.format方式 百分号方式: %[(name)][flags][width].[precision]typecode [  ]:表示 ...

  2. linux backtrace()详细使用说明,分析Segmentation fault【转】

    转自:http://velep.com/archives/1032.html 在此之前,开发eCos应用程序时,经常碰到程序挂掉后,串口打印输出一大串让人看不懂的数据.今天才明白,原来这些数据是程序挂 ...

  3. linux 串口驱动(三) 【转】

    转自:http://blog.chinaunix.net/uid-27717694-id-3495825.html 三.串口的打开在用户空间执行open操作的时候,就会执行uart_ops->o ...

  4. node.js 安装 测试

    2014年5月1日 18:48:01 安装: 系统是centos,里边的python版本是2.4,但是node.js 源码tar包安装要求是 2.6 或者 2.7 下载python 2.7编译安装,注 ...

  5. Java @Override 注解

    @Override注解,不是关键字,但可以当关键字使用,可以选择添加这个注解,在你不留心重载而并非复写了该方法时,编译器就会产生一条错误:The method doh(Milhouse) of typ ...

  6. Python 协程检测Kubernetes服务端口

    一.需求分析 在上一篇文章,链接如下: https://www.cnblogs.com/xiao987334176/p/10237551.html 已经得到了需要的数据,现在需要对这些端口做检测,判断 ...

  7. ERP渠道文档详细和修改(二十五)

    前端代码: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChannelD ...

  8. hive的实现机制

    hive利用hdfs存储数据文件,利用MapReduce查询数据. 数据库:支持在线联机业务(实时.事务控制) 数据仓库:存储历史数据,面向主题的.主要用于离线数据分析的.

  9. 【Java】 二叉树的遍历(递归与循环+层序遍历)

    在[Java] 大话数据结构(9) 树(二叉树.线索二叉树)一文中,已经实现了采用递归方法的前.中.后序遍历,本文补充了采用循环的实现方法.以及层序遍历并进行了一个总结. 递归实现 /* * 前序遍历 ...

  10. SSIS组件——Merge、Merge Join、Union All