C # a more elegant way to replace switch statements,

Source: Internet
Author: User

C # a more elegant way to replace switch statements,

 

Today, I encountered a condition for using the switch statement in the project, but the problem is that there are many conditions. There are about dozens of conditions, and case Judgments are made when the screen is full, is there a more elegant way to replace switch statements?


Suppose there is a scenario where malls often adopt different discount schemes based on the situation. If there are few discount schemes, consider using the switch statement for judgment. However, if there are dozens or even hundreds of discounts, the switch statement is not elegant enough.

 

First, a discount interface.

 

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

 

The Parameter policy is used to receive enumeration items related to discounts. The parameter orginPrice indicates the price before discounts. The following enumerated discounts are available:

 

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

 

Implement the IValueProcessor interface and adopt different algorithms based on different metrics yenum.

 

   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;
            }
        }
    }

 

The client call is as follows:

 

        static void Main(string[] args)
        {
Console. WriteLine ("Enter the discount policy." 0 "means off," 1 "means off," 3 "means off, and" 4 "means off :");
            string policy = Console.ReadLine();
            decimal originPrice = (decimal)100.00;
Console. WriteLine ("price before discount:" + originPrice );
            MyValueProcessor processor = new MyValueProcessor();
Console. WriteLine ("the discounted price is:" + processor. DaZhe (short. Parse (policy), originPrice ));
            Console.ReadKey();
        }

 

There is not much problem with the above writing method. Is there a switch replacement judgment? Is it a more elegant writing method?

 

In the DaZhe (short policy, decimal orginPrice) method of the MyValueProcessor class, a short-type parameter and a decimal-type parameter are received, and the decimal type is returned. Inside the method, take the short type form parameter as the condition for judging the switch statement, and then use different algorithms to get the return value. Further Abstraction: the short type is used as the key in the dictionary set, and the algorithm, that is, the delegate, is used as the value of the dictionary set. In this way, we can encapsulate various discount schemes in dictionary sets. Modify as follows:

 

    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;
        }
    }

 

In this way, in the DaZhe (short policy, decimal orginPrice) method, you only need to judge whether the passed short type real parameter is the key of the dictionary set.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.