今天在项目中遇到了使用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. flask基础之请求钩子(十二)

    前言 什么是请求钩子?在客户端和服务器交互的过程中,有些准备工作或扫尾工作需要统一处理,为了让每个视图函数避免编写重复功能的代码,flask提供了统一的接口可以添加这些处理函数,即请求钩子. 请求钩子 ...

  2. 分析占用了大量CPU处理时间的是Java进程中哪个线程

    下面是详细步骤: 1. 首先确定进程的 ID ,可以使用 jps -v 或者 top 命令直接查看 2. 查看该进程中哪个线程占用大量 CPU,执行 top -H -p [PID] 结果如下: 可以发 ...

  3. 003_vim使用tip

    vim 使用tip 编写python程序 自动插入头信息: #!/usr/bin/env python # coding=utf-8 输入.或按TAB键会触发代码补全功能 :w保存代码之后会自动检查代 ...

  4. 文字小于12px时,设置line-height不居中问题

    设置了文字了小于12px时,会存在设置了line-height的不生效的问题,主要是由于基线的问题,这篇文章解释的很清楚,有兴趣的可以看下https://blog.csdn.net/q12151634 ...

  5. Django Rest Framework-APIView源码分析

    class APIView(View): # The following policies may be set at either globally, or per-view. renderer_c ...

  6. ajax调用WebService 不能跨域

    http://www.cnblogs.com/dojo-lzz/p/4265637.html "Access-Control-Allow-Origin":'http://local ...

  7. java LinkedList(链表)

    LinkedList也像ArrayList一样实现了基本的List接口,但是它执行某些操作(在List的中间插入和移除)时比ArrayList更高效,但在随机访问方面却要逊色一些 LinkedList ...

  8. mavean项目的jar位置的影响

    由于项目的数据库需求改变了,有mysql数据库变为oracle的,那么对于项目就是需要改变数据库连接池.这个项目运用了mavean框架,那么下载jar在pom.xml文件中填写就可以了,但是oracl ...

  9. js下判断 iframe 是否加载完成的完美方法

    一般来说,我们判断 iframe 是否加载完成其实与 判断JavaScript 文件是否加载完成.     采用的方法很类似: var iframe = document.createElement( ...

  10. 【LOJ】#2106. 「JLOI2015」有意义的字符串

    题解 点一个技能点叫特征方程 就是 \(a_{n + 2} = c_1 a_{n + 1} + c_2 a_{n}\) \(x^2 = c_1 x + c_2\) 解出两根来是\(x_1,x_2\) ...