用于状态处理的多态枚举

2023-12-23

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

例如

enum Pricemethod
{
    Max,
    Min,
    Average
}

...我有一篇类文章

 public class Article 
{
    private List<Double> _pricehistorie;

    public List<Double> 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 调用特定的 Calculation 并返回它。

get { return CalculatedPrice(Pricemethod); }

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


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

你不知道。枚举只是一种令人愉快的写作语法const int.

考虑这个模式:

public abstract class PriceMethod
{
  // Prevent inheritance from outside.
  private PriceMethod() {}

  public abstract decimal Invoke(IEnumerable<decimal> sequence);

  public static PriceMethod Max = new MaxMethod();

  private sealed class MaxMethod : PriceMethod
  {
    public override decimal Invoke(IEnumerable<decimal> sequence)
    {
      return sequence.Max();
    }
  }

  // etc, 
}

现在你可以说

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

用户可以说

myArticle.PriceMethod = PriceMethod.Max;
decimal price = myArticle.Price;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用于状态处理的多态枚举 的相关文章

随机推荐