Polymorphic Enums for state handling

后端 未结 2 544
隐瞒了意图╮
隐瞒了意图╮ 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 20:10

    how do I handle enums without using switch or if statements in C#?

    You don't. enums are just a pleasant syntax for writing const int.

    Consider this pattern:

    public abstract class PriceMethod
    {
      // Prevent inheritance from outside.
      private PriceMethod() {}
    
      public abstract decimal Invoke(IEnumerable sequence);
    
      public static PriceMethod Max = new MaxMethod();
    
      private sealed class MaxMethod : PriceMethod
      {
        public override decimal Invoke(IEnumerable sequence)
        {
          return sequence.Max();
        }
      }
    
      // etc, 
    }
    

    And now you can say

    public decimal Price
    {
        get { return PriceMethod.Invoke(this.PriceHistory); }
    }
    

    And the user can say

    myArticle.PriceMethod = PriceMethod.Max;
    decimal price = myArticle.Price;
    

提交回复
热议问题