用于状态处理的多态Enum

如何在不使用C#中的switch或if语句的情况下处理枚举?

例如

enum Pricemethod { Max, Min, Average } 

……我有一篇文章

  public class Article { private List _pricehistorie; public List Pricehistorie { get { return _pricehistorie; } set { _pricehistorie = value; } } public Pricemethod Pricemethod { get; set; } public double Price { get { switch (Pricemethod) { case Pricemethod.Average: return Average(); case Pricemethod.Max: return Max(); case Pricemethod.Min: return Min(); } } } } 

我想避免使用switch语句并使其成为通用语句。

对于特定的Pricemethod,请调用特定的计算并将其返回。

 get { return CalculatedPrice(Pricemethod); } 

这里使用的模式可能有人有一个很好的实现想法。 已经搜索了状态模式,但我不认为这是正确的。

如何在不使用C#中的switchif语句的情况下处理枚举?

你没有。 枚举只是编写const int一种令人愉快的语法。

考虑这种模式:

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

现在你可以说

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

用户可以说

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

您可以创建一个interface ,以及实现它的class es:

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

编辑:另一种方法是使用Dictionary来映射Func ,因此您不必为此创建类(此代码基于Servy的代码,自从删除了他的答案):

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