Polymorphic Enums for state handling

后端 未结 2 545
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 19:22

how do i handle Enums without using switch or if statements in C#?

For Example

enum Pricemethod
{
    Max,
    Min,
    Average
}

... a

2条回答
  •  离开以前
    2021-02-04 19:48

    You could create an interface, and classes that implement it:

    public interface IPriceMethod
    {
        double Calculate(IList priceHistorie);
    }
    public class AveragePrice : IPriceMethod
    {
        public double Calculate(IList priceHistorie)
        {
            return priceHistorie.Average();
        }
    }
    // other classes
    public class Article 
    {
        private List _pricehistorie;
    
        public List Pricehistorie
        {
            get { return _pricehistorie; }
            set { _pricehistorie = value; }
        }
    
        public IPriceMethod Pricemethod { get; set; }
    
        public double Price
        {
            get {
                return Pricemethod.Calculate(Pricehistorie);
            }
        }
    
    }
    

    Edit: another way is using a Dictionary to map Funcs, so you don't have to create classes just for this (this code is based on code by Servy, who since deleted his answer):

    public class Article
    {
        private static readonly Dictionary, double>>
            priceMethods = new Dictionary, double>>
            {
                {Pricemethod.Max,ph => ph.Max()},
                {Pricemethod.Min,ph => ph.Min()},
                {Pricemethod.Average,ph => ph.Average()},
            };
    
        public Pricemethod Pricemethod { get; set; }
        public List Pricehistory { get; set; }
    
        public double Price
        {
            get
            {
                return priceMethods[Pricemethod](Pricehistory);
            }
        }
    }
    

提交回复
热议问题