国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C#中一種替換switch語句更優雅的寫法

2019-11-17 02:15:45
字體:
來源:轉載
供稿:網友

C#中一種替換switch語句更優雅的寫法

今天在項目中遇到了使用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 = (dec
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁津县| 古交市| 宁阳县| 崇义县| 吉安市| 朝阳区| 出国| 长乐市| 甘孜| 海林市| 东宁县| 宁南县| 丁青县| 兴业县| 文成县| 金寨县| 呼伦贝尔市| 志丹县| 高台县| 灵璧县| 武邑县| 金阳县| 深州市| 信阳市| 油尖旺区| 怀集县| 永善县| 高雄市| 健康| 轮台县| 邳州市| 铁岭县| 沁源县| 山阴县| 当雄县| 浏阳市| 章丘市| 永福县| 汉阴县| 汉阴县| 河津市|