国产探花免费观看_亚洲丰满少妇自慰呻吟_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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 海城市| 全椒县| 罗山县| 高青县| 方城县| 章丘市| 拜城县| 玉环县| 云安县| 大名县| 平陆县| 新宾| 贵阳市| 蒲城县| 娱乐| 麟游县| 江川县| 九龙坡区| 衡阳县| 济源市| 集安市| 荆州市| 潜江市| 府谷县| 名山县| 调兵山市| 南木林县| 建德市| 揭东县| 重庆市| 旺苍县| 山丹县| 菏泽市| 济阳县| 拜城县| 平昌县| 平昌县| 定陶县| 太仓市| 昌邑市| 临汾市|